<!DOCTYPE html>
<html lang="zh-CN">

  
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  <meta name="author" content="董沅鑫, yuanxin.me@gmail.com">
  
  
  
  <title>C#基础教程 | 朽年的博客</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="C#,笔记,C#,">
  

  <script>
    console.log('\n%c Hexo-theme-bmw v4.0 ' + '%c 🎉 https://github.com/dongyuanxin/theme-bmw 🎉\n' + '\n%c View demo online ' + '%c 🔍 https://godbmw.com/ 🔍  \n' , 'color: #fadfa3; background: #030307; padding:3px 0;', '', 'color: #fadfa3; background: #030307; padding:3px 0;', '');
  </script>

  

  

  
    <link rel="icon" href="/images/favicon.ico">
    <link rel="apple-touch-icon" href="/images/touch-icon.png">
  

  <link href="https://cdn.bootcss.com/fancybox/3.5.2/jquery.fancybox.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/icon/iconfont.css">
<link rel="stylesheet" href="/css/github-markdown.css">
<link rel="stylesheet" href="/css/highlight.css">

  <script src="/js/util.js"></script>
<script src="/js/valine.min.js"></script>

  

  
    <link href="https://cdn.bootcss.com/aplayer/1.10.1/APlayer.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/aplayer/1.10.1/APlayer.min.js" async></script>
  

  
    <link href="https://cdn.bootcss.com/social-share.js/1.0.16/css/share.min.css" rel="stylesheet">
  
  
  <script src="//cdn.bootcss.com/jquery/3.3.1/jquery.min.js" async></script>
  
  
    <script src="//cdn.jsdelivr.net/npm/leancloud-storage@3.11.0/dist/av-min.js"></script>
  

</head>

  <body>

    

    <div id="app">

      <div class="header-wrap">
  <header>
    <div class="site-brand">
      <div class="site-title">
        <a href="/">朽年的博客</a>
      </div>
    </div>
    <nav class="site-navigation">
      <ul class="nav-menu">
      
        <li class="nav-item" data-path="/">
          
            <a href="/" target="_self">
              主页
            </a>
          
        </li>
      
        <li class="nav-item" data-path="/archives/">
          
            <a href="/archives/" target="_self">
              归档
            </a>
          
        </li>
      
        <li class="nav-item" data-path="/categories/">
          
            <a href="/categories/" target="_self">
              分类云
            </a>
          
        </li>
      
        <li class="nav-item" data-path="/tags/">
          
            <a href="/tags/" target="_self">
              标签云
            </a>
          
        </li>
      
        <li class="nav-item" data-path="/friends/">
          
            <a href="/friends/" target="_self">
              友链
            </a>
          
        </li>
      
        <li class="nav-item" data-path="/about/">
          
            <a href="/about/" target="_self">
              关于
            </a>
          
        </li>
      
        <li class="nav-item" data-path>
          
            <a href="javascript:void(0);" v-else>抓到我</a>
            <ul class="nav-menu--dropdown">
              
                <li>
                  <a href="https://github.com/tangbeida" target="_blank">
                    Github
                  </a>
                </li>
              
                <li>
                  <a href="https://www.zhihu.com/people/tang-bei-da-53/activities" target="_blank">
                    知乎
                  </a>
                </li>
              
            </ul>
          
        </li>
      
      </ul>
    </nav>
    <i class="iconfont icon-menu"></i>
  </header>
</div>

<script>
  let links = document.querySelectorAll('.nav-item');
  for(let link of links){
    let childrenLink = link.querySelector('ul');
    link.addEventListener('mouseenter', () => {
      if(childrenLink) {
        childrenLink.className = "nav-menu--dropdown active";
      }
    })
    link.addEventListener('mouseleave', () => {
      if(childrenLink) {
        childrenLink.className = "nav-menu--dropdown";
      }
    })
  }
  let rootRealPath = getRealPath(window.location.pathname, true);
  for(let link of links) {
    let linkPath = link.getAttribute("data-path");
    if(linkPath && getRealPath(linkPath, true) === rootRealPath) {
      link.className = "nav-item hover";
    }
  }

  let iconMenu = document.querySelector("i.iconfont.icon-menu"),
    iconMenuClicked = false;
  let navDOM = document.querySelector("nav.site-navigation");
  iconMenu.addEventListener("click", () => {
    iconMenuClicked 
      ? navDOM.className = "site-navigation active"
      : navDOM.className = "site-navigation";
    iconMenuClicked = !iconMenuClicked;
  })
</script>

      








<div class="container post-index">

  

<div class="post">
  <h1 class="article-title">
    <span>C#基础教程</span>
  </h1>
  <div class="article-top-meta">
    <span>
      发布 : 
      2018-03-12
    </span>
    
      <span>
        分类 : 
          <a href="/categories/C/">
            C#
          </a>
      </span>
    
    
      <span>
        浏览 : <span class="article-timer" data-identity="C-教程"></span>
      </span>
    
  </div>

  

  <div class="article-content">
    <div class="markdown-body">
      <p></p>
<h1 id="C-基础教程"><a href="#C-基础教程" class="headerlink" title="C#基础教程"></a>C#基础教程</h1><h2 id="一-C-简介"><a href="#一-C-简介" class="headerlink" title="一.C#简介"></a>一.C#简介</h2><p>C# 是一个简单的、现代的、通用的、面向对象的编程语言，它是由微软（Microsoft）开发的。本教程将告诉您基础的 C# 编程，同时将向您讲解 C# 编程语言相关的各种先进理念。</p>
<ul>
<li><p>C# 是一个现代的、通用的、面向对象的编程语言，它是由微软（Microsoft）开发的，由 Ecma 和 ISO 核准认可的。</p>
</li>
<li><p>C# 是由 Anders Hejlsberg 和他的团队在 .Net 框架开发期间开发的。</p>
</li>
<li><p>C# 是专为公共语言基础结构（CLI）设计的。CLI 由可执行代码和运行时环境组成，允许在不同的计算机平台和体系结构上使用各种高级语言。</p>
<p><strong>下面列出了 C# 成为一种广泛应用的专业语言的原因：</strong></p>
<ul>
<li>现代的、通用的编程语言。</li>
<li>面向对象。</li>
<li>面向组件。</li>
<li>容易学习。</li>
<li>结构化语言。</li>
<li>它产生高效率的程序。</li>
<li>它可以在多种计算机平台上编译。</li>
<li>.Net 框架的一部分</li>
</ul>
</li>
</ul>
<h3 id="1-C-强大的编程功能"><a href="#1-C-强大的编程功能" class="headerlink" title="1.C#强大的编程功能"></a><strong>1.C#强大的编程功能</strong></h3><p>虽然 C# 的构想十分接近于传统高级语言 C 和 C++，是一门面向对象的编程语言，但是它与 Java 非常相似，有许多强大的编程功能，因此得到广大程序员的青睐。</p>
<p><strong>下面列出 C# 一些重要的功能：</strong></p>
<ul>
<li>布尔条件（Boolean Conditions）</li>
<li>自动垃圾回收（Automatic Garbage Collection）</li>
<li>标准库（Standard Library）</li>
<li>组件版本（Assembly Versioning）</li>
<li>属性（Properties）和事件（Events）</li>
<li>委托（Delegates）和事件管理（Events Management）</li>
<li>易于使用的泛型（Generics）</li>
<li>索引器（Indexers）</li>
<li>条件编译（Conditional Compilation）</li>
<li>简单的多线程（Multithreading）</li>
<li>LINQ 和 Lambda 表达式</li>
<li>集成 Windows</li>
</ul>
<h2 id="二-C-环境"><a href="#二-C-环境" class="headerlink" title="二.C#环境"></a>二.C#环境</h2><p>在这一章中，我们将讨论创建 C# 编程所需的工具。我们已经提到 C# 是 .Net 框架的一部分，且用于编写 .Net 应用程序。因此，在讨论运行 C# 程序的可用工具之前，让我们先了解一下 C# 与 .Net 框架之间的关系。</p>
<h3 id="1-Net框架（-Net-Framework）"><a href="#1-Net框架（-Net-Framework）" class="headerlink" title="1. .Net框架（.Net Framework）"></a><strong>1. .Net框架（.Net Framework）</strong></h3><p>Net 框架是一个创新的平台，能帮您编写出下面类型的应用程序：</p>
<ul>
<li>Windows 应用程序</li>
<li>Web 应用程序</li>
<li>Web 服务</li>
</ul>
<p>.Net 框架应用程序是多平台的应用程序。框架的设计方式使它适用于下列各种语言：C#、C++、Visual Basic、Jscript、COBOL 等等。所有这些语言可以访问框架，彼此之间也可以互相交互。</p>
<p>.Net 框架由一个巨大的代码库组成，用于 C# 等客户端语言。下面列出一些 .Net 框架的组件：</p>
<ul>
<li>公共语言运行库（Common Language Runtime - CLR）</li>
<li>.Net 框架类库（.Net Framework Class Library）</li>
<li>公共语言规范（Common Language Specification）</li>
<li>通用类型系统（Common Type System）</li>
<li>元数据（Metadata）和组件（Assemblies）</li>
<li>Windows 窗体（Windows Forms）</li>
<li>ASP.Net 和 ASP.Net AJAX</li>
<li>ADO.Net</li>
<li>Windows 工作流基础（Windows Workflow Foundation - WF）</li>
<li>Windows 显示基础（Windows Presentation Foundation）</li>
<li>Windows 通信基础（Windows Communication Foundation - WCF）</li>
<li>LINQ</li>
</ul>
<h3 id="2-C-的集成开发环境（Integrated-Development-Environment-IDE）"><a href="#2-C-的集成开发环境（Integrated-Development-Environment-IDE）" class="headerlink" title="2. C# 的集成开发环境（Integrated Development Environment - IDE）"></a><strong>2. C# 的集成开发环境（Integrated Development Environment - IDE）</strong></h3><p>微软（Microsoft）提供了下列用于 C# 编程的开发工具：</p>
<ul>
<li>Visual Studio 2010 (VS)</li>
<li>Visual C# 2010 Express (VCE)</li>
<li>Visual Web Developer</li>
</ul>
<p>后面两个是免费使用的，可从微软官方网址下载。使用这些工具，您可以编写各种 C# 程序，从简单的命令行应用程序到更复杂的应用程序。您也可以使用基本的文本编辑器（比如 Notepad）编写 C# 源代码文件，并使用命令行编译器（.NET 框架的一部分）编译代码为组件。</p>
<p>Visual C# Express 和 Visual Web Developer Express 版本是 Visual Studio 的定制版本，且具有相同的外观和感观。它们保留 Visual Studio 的大部分功能。</p>
<h3 id="3-在-Linux-或-Mac-OS-上编写-C-程序"><a href="#3-在-Linux-或-Mac-OS-上编写-C-程序" class="headerlink" title="3. 在 Linux 或 Mac OS 上编写 C# 程序"></a><strong>3. 在 Linux 或 Mac OS 上编写 C# 程序</strong></h3><p>虽然 .NET 框架是运行在 Windows 操作系统上，但是也有一些运行于其它操作系统上的版本可供选择。<strong>Mono</strong> 是 .NET 框架的一个开源版本，它包含了一个 C# 编译器，且可运行于多种操作系统上，比如各种版本的 Linux 和 Mac OS</p>
<p>Mono 的目的不仅仅是跨平台地运行微软 .NET 应用程序，而且也为 Linux 开发者提供了更好的开发工具。Mono 可运行在多种操作系统上，包括 Android、BSD、iOS、Linux、OS X、Windows、Solaris 和 UNIX。</p>
<h2 id="三-C-程序结构"><a href="#三-C-程序结构" class="headerlink" title="三. C# 程序结构"></a>三. <em>C# 程序结构</em></h2><p>在我们学习 C# 编程语言的基础构件块之前，让我们先看一下 C# 的最小的程序结构，以便作为接下来章节的参考</p>
<h3 id="1-C-Hello-World实例"><a href="#1-C-Hello-World实例" class="headerlink" title="1. C#Hello World实例"></a><strong>1. C#Hello World实例</strong></h3><p><strong>一个 C# 程序主要包括以下部分：</strong></p>
<ul>
<li>命名空间声明（Namespace declaration）</li>
<li>一个 class</li>
<li>Class 方法</li>
<li>Class 属性</li>
<li>一个 Main 方法</li>
<li>语句（Statements）&amp; 表达式（Expressions）</li>
<li>注释</li>
</ul>
<p>让我们看一个可以打印出 “Hello World” 的简单的代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace HelloWorldApplication</span><br><span class="line">&#123;</span><br><span class="line">   class HelloWorld</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         /* 我的第一个 C# 程序*/</span><br><span class="line">         Console.WriteLine(&quot;Hello World&quot;);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Hello World</span><br></pre></td></tr></table></figure>
<p><strong>让我们看一下上面程序的各个部分：</strong></p>
<ul>
<li>程序的第一行 <strong>using System;</strong> - <strong>using</strong> 关键字用于在程序中包含 <strong>System</strong> 命名空间。 一个程序一般有多个 <strong>using</strong> 语句。</li>
<li>下一行是 <strong>namespace</strong> 声明。一个 <strong>namespace</strong> 里包含了一系列的类。<em>HelloWorldApplication</em> 命名空间包含了类 <em>HelloWorld</em>。</li>
<li>下一行是 <strong>class</strong> 声明。类 <em>HelloWorld</em> 包含了程序使用的数据和方法声明。类一般包含多个方法。方法定义了类的行为。在这里，<em>HelloWorld</em> 类只有一个 <strong>Main</strong> 方法。</li>
<li>下一行定义了 <strong>Main</strong> 方法，是所有 C# 程序的 <strong>入口点</strong>。<strong>Main</strong> 方法说明当执行时 类将做什么动作。</li>
<li>下一行 /<em>…</em>/ 将会被编译器忽略，且它会在程序中添加额外的 <strong>注释</strong>。</li>
<li>Main 方法通过语句 Console.WriteLine(“Hello World”); 指定了它的行为。<em>WriteLine</em> 是一个定义在 <em>System</em> 命名空间中的 <em>Console</em> 类的一个方法。该语句会在屏幕上显示消息 “Hello, World!”。</li>
<li>最后一行 <strong>Console.ReadKey();</strong> 是针对 VS.NET 用户的。这使得程序会等待一个按键的动作，防止程序从 Visual Studio .NET 启动时屏幕会快速运行并关闭。</li>
</ul>
<p><strong>以下几点值得注意：</strong></p>
<ul>
<li>C# 是大小写敏感的。</li>
<li>所有的语句和表达式必须以分号（;）结尾。</li>
<li>程序的执行从 Main 方法开始。</li>
<li>与 Java 不同的是，文件名可以不同于类的名称。</li>
</ul>
<h3 id="2-编译-amp-执行-C-程序"><a href="#2-编译-amp-执行-C-程序" class="headerlink" title="2. 编译 &amp; 执行 C# 程序"></a><strong>2. 编译 &amp; 执行 C# 程序</strong></h3><p><strong>如果您使用 Visual Studio.Net 编译和执行 C# 程序，请按下面的步骤进行：</strong></p>
<ul>
<li>启动 Visual Studio。</li>
<li>在菜单栏上，选择 File -&gt; New -&gt; Project。</li>
<li>从模板中选择 Visual C#，然后选择 Windows。</li>
<li>选择 Console Application。</li>
<li>为您的项目制定一个名称，然后点击 OK 按钮。</li>
<li>新项目会出现在解决方案资源管理器（Solution Explorer）中。</li>
<li>在代码编辑器（Code Editor）中编写代码。</li>
<li>点击 Run 按钮或者按下 F5 键来运行程序。会出现一个命令提示符窗口（Command Prompt window），显示 Hello World。</li>
</ul>
<p><strong>您也可以使用命令行代替 Visual Studio IDE 来编译 C# 程序：</strong></p>
<ul>
<li>打开一个文本编辑器，添加上面提到的代码。</li>
<li>保存文件为 <strong>helloworld.cs</strong>。</li>
<li>打开命令提示符工具，定位到文件所保存的目录。</li>
<li>键入 <strong>csc helloworld.cs</strong> 并按下 enter 键来编译代码。</li>
<li>如果代码没有错误，命令提示符会进入下一行，并生成 <strong>helloworld.exe</strong> 可执行文件。</li>
<li>接下来，键入 <strong>helloworld</strong> 来执行程序。</li>
<li>您将看到 “Hello World” 打印在屏幕上。</li>
</ul>
<h2 id="四-C-基本语法"><a href="#四-C-基本语法" class="headerlink" title="四. C#基本语法"></a>四. C#基本语法</h2><p>C# 是一种面向对象的编程语言。在面向对象的程序设计方法中，程序由各种相互交互的对象组成。相同种类的对象通常具有相同的类型，或者说，是在相同的 class 中。例如，以 Rectangle（矩形）对象为例。它具有 length 和 width 属性。根据设计，它可能需要接受这些属性值、计算面积和显示细节。</p>
<p>让我们来看看一个 Rectangle（矩形）类的实现，并借此讨论 C# 的基本语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace RectangleApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Rectangle</span><br><span class="line">    &#123;</span><br><span class="line">        // 成员变量</span><br><span class="line">        double length;</span><br><span class="line">        double width;</span><br><span class="line">        public void Acceptdetails()</span><br><span class="line">        &#123;</span><br><span class="line">            length = 4.5;    </span><br><span class="line">            width = 3.5;</span><br><span class="line">        &#125;</span><br><span class="line">        public double GetArea()</span><br><span class="line">        &#123;</span><br><span class="line">            return length * width;</span><br><span class="line">        &#125;</span><br><span class="line">        public void Display()</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;Length: &#123;0&#125;&quot;, length);</span><br><span class="line">            Console.WriteLine(&quot;Width: &#123;0&#125;&quot;, width);</span><br><span class="line">            Console.WriteLine(&quot;Area: &#123;0&#125;&quot;, GetArea());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    class ExecuteRectangle</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Rectangle r = new Rectangle();</span><br><span class="line">            r.Acceptdetails();</span><br><span class="line">            r.Display();</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>当上面的代码被编译和执行时，它会产生下列结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Length: 4.5</span><br><span class="line">Width: 3.5</span><br><span class="line">Area: 15.75</span><br></pre></td></tr></table></figure>
<h3 id="1-using-关键字"><a href="#1-using-关键字" class="headerlink" title="1.using 关键字"></a><strong><em>1.using</em> 关键字</strong></h3><p>在任何 C# 程序中的第一条语句都是：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br></pre></td></tr></table></figure>
<p><strong>using</strong> 关键字用于在程序中包含命名空间。一个程序可以包含多个 using 语句。</p>
<h3 id="2-class-关键字"><a href="#2-class-关键字" class="headerlink" title="2.class 关键字"></a><strong><em>2.class</em> 关键字</strong></h3><p><strong>class</strong> 关键字用于声明一个类。</p>
<h3 id="3-C-中的注释"><a href="#3-C-中的注释" class="headerlink" title="3.C# 中的注释"></a><strong>3.C# 中的注释</strong></h3><p>注释是用于解释代码。编译器会忽略注释的条目。在 C# 程序中，多行注释以 /<em> 开始，并以字符 </em>/ 终止，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/* This program demonstrates</span><br><span class="line">The basic syntax of C# programming </span><br><span class="line">Language */</span><br></pre></td></tr></table></figure>
<p>单行注释是用 ‘//‘ 符号表示。例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#125;//end class Rectangle</span><br></pre></td></tr></table></figure>
<h3 id="4-成员变量"><a href="#4-成员变量" class="headerlink" title="4.成员变量"></a><strong>4.成员变量</strong></h3><p>变量是类的属性或数据成员，用于存储数据。在上面的程序中，<em>Rectangle</em> 类有两个成员变量，名为 <em>length</em> 和 <em>width</em>。</p>
<h3 id="5-成员函数"><a href="#5-成员函数" class="headerlink" title="5.成员函数"></a><strong>5.成员函数</strong></h3><p>函数是一系列执行指定任务的语句。类的成员函数是在类内声明的。我们举例的类 Rectangle 包含了三个成员函数： <em>AcceptDetails</em>、<em>GetArea</em>和 <em>Display</em>。</p>
<h3 id="6-实例化一个类"><a href="#6-实例化一个类" class="headerlink" title="6.实例化一个类"></a><strong>6.实例化一个类</strong></h3><p>在上面的程序中，类 <em>ExecuteRectangle</em> 是一个包含 <em>Main()</em> 方法和实例化 <em>Rectangle</em> 类的类。</p>
<h3 id="7-标识符"><a href="#7-标识符" class="headerlink" title="7.标识符"></a><strong>7.标识符</strong></h3><p>标识符是用来识别类、变量、函数或任何其它用户定义的项目。在 C# 中，类的命名必须遵循如下基本规则：</p>
<ul>
<li>标识符必须以字母、下划线或 @ 开头，后面可以跟一系列的字母、数字（ 0 - 9 ）、下划线（ _ ）、@。</li>
<li>标识符中的第一个字符不能是数字。</li>
<li>标识符必须不包含任何嵌入的空格或符号，比如 ? - +! # % ^ &amp; * ( ) [ ] { } . ; : “ ‘ / \。</li>
<li>标识符不能是 C# 关键字。除非它们有一个 @ 前缀。 例如，@if 是有效的标识符，但 if 不是，因为 if 是关键字。</li>
<li>标识符必须区分大小写。大写字母和小写字母被认为是不同的字母。</li>
<li>不能与C#的类库名称相同。</li>
</ul>
<h3 id="8-C-关键字"><a href="#8-C-关键字" class="headerlink" title="8.C# 关键字"></a><strong>8.C# 关键字</strong></h3><p>关键字是 C# 编译器预定义的保留字。这些关键字不能用作标识符，但是，如果您想使用这些关键字作为标识符，可以在关键字前面加上 @ 字符作为前缀。</p>
<p>在 C# 中，有些关键字在代码的上下文中有特殊的意义，如 get 和 set，这些被称为上下文关键字（contextual keywords）。</p>
<p>下表列出了 C# 中的保留关键字（Reserved Keywords）和上下文关键字（Contextual Keywords）：</p>
<table>
<thead>
<tr>
<th><strong>保留关键字</strong></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>abstract</td>
<td>as</td>
<td>base</td>
<td>bool</td>
<td>break</td>
<td>byte</td>
<td>case</td>
</tr>
<tr>
<td>catch</td>
<td>char</td>
<td>checked</td>
<td>class</td>
<td>const</td>
<td>continue</td>
<td>decimal</td>
</tr>
<tr>
<td>default</td>
<td>delegate</td>
<td>do</td>
<td>double</td>
<td>else</td>
<td>enum</td>
<td>event</td>
</tr>
<tr>
<td>explicit</td>
<td>extern</td>
<td>false</td>
<td>finally</td>
<td>fixed</td>
<td>float</td>
<td>for</td>
</tr>
<tr>
<td>foreach</td>
<td>goto</td>
<td>if</td>
<td>implicit</td>
<td>in</td>
<td>in (genericmodifier)</td>
<td>int</td>
</tr>
<tr>
<td>interface</td>
<td>internal</td>
<td>is</td>
<td>lock</td>
<td>long</td>
<td>namespace</td>
<td>new</td>
</tr>
<tr>
<td>null</td>
<td>object</td>
<td>operator</td>
<td>out</td>
<td>out(genericmodifier)</td>
<td>override</td>
<td>params</td>
</tr>
<tr>
<td>private</td>
<td>protected</td>
<td>public</td>
<td>readonly</td>
<td>ref</td>
<td>return</td>
<td>sbyte</td>
</tr>
<tr>
<td>sealed</td>
<td>short</td>
<td>sizeof</td>
<td>stackalloc</td>
<td>static</td>
<td>string</td>
<td>struct</td>
</tr>
<tr>
<td>switch</td>
<td>this</td>
<td>throw</td>
<td>true</td>
<td>try</td>
<td>typeof</td>
<td>uint</td>
</tr>
<tr>
<td>ulong</td>
<td>unchecked</td>
<td>unsafe</td>
<td>ushort</td>
<td>using</td>
<td>virtual</td>
<td>void</td>
</tr>
<tr>
<td>volatile</td>
<td>while</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><strong>上下文关键字</strong></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>add</td>
<td>alias</td>
<td>ascending</td>
<td>descending</td>
<td>dynamic</td>
<td>from</td>
<td>get</td>
</tr>
<tr>
<td>global</td>
<td>group</td>
<td>into</td>
<td>join</td>
<td>let</td>
<td>orderby</td>
<td>partial(type)</td>
</tr>
<tr>
<td>partial(method)</td>
<td>remove</td>
<td>select</td>
<td>set</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<h2 id="五-C-数据类型"><a href="#五-C-数据类型" class="headerlink" title="五.C# 数据类型"></a>五.C# 数据类型</h2><p>在 C# 中，变量分为以下几种类型：</p>
<ul>
<li>值类型（Value types）</li>
<li>引用类型（Reference types）</li>
<li>指针类型（Pointer types）</li>
</ul>
<h3 id="1-值类型（Value-types）"><a href="#1-值类型（Value-types）" class="headerlink" title="1.值类型（Value types）"></a><strong>1.值类型（Value types）</strong></h3><p>值类型变量可以直接分配给一个值。它们是从类 <strong>System.ValueType</strong> 中派生的。</p>
<p>值类型直接包含数据。比如 <strong>int、char、float</strong>，它们分别存储数字、字符、浮点数。当您声明一个 <strong>int</strong> 类型时，系统分配内存来存储值。</p>
<p>下表列出了 C# 2010 中可用的值类型：</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>描述</th>
<th>范围</th>
<th>默认值</th>
</tr>
</thead>
<tbody>
<tr>
<td>bool</td>
<td>布尔值</td>
<td>True 或 False</td>
<td>False</td>
</tr>
<tr>
<td>byte</td>
<td>8 位无符号整数</td>
<td>0 到 255</td>
<td>0</td>
</tr>
<tr>
<td>char</td>
<td>16 位 Unicode 字符</td>
<td>U +0000 到 U +ffff</td>
<td>‘\0’</td>
</tr>
<tr>
<td>decimal</td>
<td>128 位精确的十进制值，28-29 有效位数</td>
<td>(-7.9 x 1028 到 7.9 x 1028) / 100 到 28</td>
<td>0.0M</td>
</tr>
<tr>
<td>double</td>
<td>64 位双精度浮点型</td>
<td>(+/-)5.0 x 10-324 到 (+/-)1.7 x 10308</td>
<td>0.0D</td>
</tr>
<tr>
<td>float</td>
<td>32 位单精度浮点型</td>
<td>-3.4 x 1038 到 + 3.4 x 1038</td>
<td>0.0F</td>
</tr>
<tr>
<td>int</td>
<td>32 位有符号整数类型</td>
<td>-2,147,483,648 到 2,147,483,647</td>
<td>0</td>
</tr>
<tr>
<td>long</td>
<td>64 位有符号整数类型</td>
<td>-923,372,036,854,775,808 到 9,223,372,036,854,775,807</td>
<td>0L</td>
</tr>
<tr>
<td>sbyte</td>
<td>8 位有符号整数类型</td>
<td>-128 到 127</td>
<td>0</td>
</tr>
<tr>
<td>short</td>
<td>16 位有符号整数类型</td>
<td>-32,768 到 32,767</td>
<td>0</td>
</tr>
<tr>
<td>uint</td>
<td>32 位无符号整数类型</td>
<td>0 到 4,294,967,295</td>
<td>0</td>
</tr>
<tr>
<td>ulong</td>
<td>64 位无符号整数类型</td>
<td>0 到 18,446,744,073,709,551,615</td>
<td>0</td>
</tr>
<tr>
<td>ushort</td>
<td>16 位无符号整数类型</td>
<td>0 到 65,535</td>
<td>0</td>
</tr>
</tbody>
</table>
<p>如需得到一个类型或一个变量在特定平台上的准确尺寸，可以使用 <strong>sizeof</strong> 方法。表达式 <em>sizeof(type)</em> 产生以字节为单位存储对象或类型的存储尺寸。下面举例获取任何机器上 <em>int</em> 类型的存储尺寸：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line"></span><br><span class="line">namespace DataTypeApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Size of int: &#123;0&#125;&quot;, sizeof(int));</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Size of int: 4</span><br></pre></td></tr></table></figure>
<h3 id="2-引用类型（Reference-types）"><a href="#2-引用类型（Reference-types）" class="headerlink" title="2.引用类型（Reference types）"></a><strong>2.引用类型（Reference types）</strong></h3><p>引用类型不包含存储在变量中的实际数据，但它们包含对变量的引用。</p>
<p>换句话说，它们指的是一个内存位置。使用多个变量时，引用类型可以指向一个内存位置。如果内存位置的数据是由一个变量改变的，其他变量会自动反映这种值的变化。<strong>内置的</strong> 引用类型有：<strong>object</strong>、<strong>dynamic</strong> 和 <strong>string</strong>。</p>
<h3 id="3-对象（Object）类型"><a href="#3-对象（Object）类型" class="headerlink" title="3.对象（Object）类型"></a><strong>3.对象（Object）类型</strong></h3><p><strong>对象（Object）类型</strong> 是 C# 通用类型系统（Common Type System - CTS）中所有数据类型的终极基类。Object 是 System.Object 类的别名。所以对象（Object）类型可以被分配任何其他类型（值类型、引用类型、预定义类型或用户自定义类型）的值。但是，在分配值之前，需要先进行类型转换。</p>
<p>当一个值类型转换为对象类型时，则被称为 <strong>装箱</strong>；另一方面，当一个对象类型转换为值类型时，则被称为 <strong>拆箱</strong>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">object obj;</span><br><span class="line">obj = 100; // 这是装箱</span><br></pre></td></tr></table></figure>
<h3 id="4-动态（Dynamic）类型"><a href="#4-动态（Dynamic）类型" class="headerlink" title="4.动态（Dynamic）类型"></a><strong>4.动态（Dynamic）类型</strong></h3><p>您可以存储任何类型的值在动态数据类型变量中。这些变量的类型检查是在运行时发生的。</p>
<p>声明动态类型的语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dynamic &lt;variable_name&gt; = value;</span><br></pre></td></tr></table></figure>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dynamic d = 20;</span><br></pre></td></tr></table></figure>
<p>动态类型与对象类型相似，但是对象类型变量的类型检查是在编译时发生的，而动态类型变量的类型检查是在运行时发生的。</p>
<h3 id="5-字符串（String）类型"><a href="#5-字符串（String）类型" class="headerlink" title="5.字符串（String）类型"></a><strong>5.字符串（String）类型</strong></h3><p><strong>字符串（String）类型</strong> 允许您给变量分配任何字符串值。字符串（String）类型是 System.String 类的别名。它是从对象（Object）类型派生的。字符串（String）类型的值可以通过两种形式进行分配：引号和 @引号。</p>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">String str = &quot;runoob.com&quot;;</span><br></pre></td></tr></table></figure>
<p>一个 @引号字符串：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@&quot;runoob.com&quot;;</span><br></pre></td></tr></table></figure>
<p>C# string 字符串的前面可以加 @（称作”逐字字符串”）将转义字符（\）当作普通字符对待，比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">string str = @&quot;C:\Windows&quot;;</span><br></pre></td></tr></table></figure>
<p>等价于：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">string str = &quot;C:\\Windows&quot;;</span><br></pre></td></tr></table></figure>
<p>@ 字符串中可以任意换行，换行符及缩进空格都计算在字符串长度之内。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">string str = @&quot;&lt;script type=&quot;&quot;text/javascript&quot;&quot;&gt;</span><br><span class="line">    &lt;!--</span><br><span class="line">    --&gt;</span><br><span class="line">&lt;/script&gt;&quot;;</span><br></pre></td></tr></table></figure>
<p>用户自定义引用类型有：class、interface 或 delegate。我们将在以后的章节中讨论这些类型。</p>
<h3 id="6-指针类型（Pointer-types）"><a href="#6-指针类型（Pointer-types）" class="headerlink" title="6.指针类型（Pointer types）"></a><strong>6.指针类型（Pointer types）</strong></h3><p>指针类型变量存储另一种类型的内存地址。C# 中的指针与 C 或 C++ 中的指针有相同的功能。</p>
<p>声明指针类型的语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">type* identifier;</span><br></pre></td></tr></table></figure>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">char* cptr;</span><br><span class="line">int* iptr;</span><br></pre></td></tr></table></figure>
<h2 id="六-C-类型转换"><a href="#六-C-类型转换" class="headerlink" title="六.C# 类型转换"></a>六.C# 类型转换</h2><p>类型转换从根本上说是类型铸造，或者说是把数据从一种类型转换为另一种类型。在 C# 中，类型铸造有两种形式：</p>
<ul>
<li><strong>隐式类型转换</strong> - 这些转换是 C# 默认的以安全方式进行的转换, 不会导致数据丢失。例如，从小的整数类型转换为大的整数类型，从派生类转换为基类。</li>
<li><strong>显式类型转换</strong> - 显式类型转换，即强制类型转换。显式转换需要强制转换运算符，而且强制转换会造成数据丢失。</li>
</ul>
<p>下面的实例显示了一个显式的类型转换：</p>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">namespace TypeConversionApplication</span><br><span class="line">&#123;</span><br><span class="line">    class ExplicitConversion</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            double d = 5673.74;</span><br><span class="line">            int i;</span><br><span class="line">            // 强制转换 double 为 int</span><br><span class="line">            i = (int)d;</span><br><span class="line">            Console.WriteLine(i);</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">5673</span><br></pre></td></tr></table></figure>
<h3 id="1-C-类型转换方法"><a href="#1-C-类型转换方法" class="headerlink" title="1.C# 类型转换方法"></a><strong>1.C# 类型转换方法</strong></h3><p>C# 提供了下列内置的类型转换方法：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>方法 &amp; 描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><strong>ToBoolean</strong>如果可能的话，把类型转换为布尔型。</td>
</tr>
<tr>
<td>2</td>
<td><strong>ToByte</strong>把类型转换为字节类型。</td>
</tr>
<tr>
<td>3</td>
<td><strong>ToChar</strong>如果可能的话，把类型转换为单个 Unicode 字符类型。</td>
</tr>
<tr>
<td>4</td>
<td><strong>ToDateTime</strong>把类型（整数或字符串类型）转换为 日期-时间 结构。</td>
</tr>
<tr>
<td>5</td>
<td><strong>ToDecimal</strong>把浮点型或整数类型转换为十进制类型。</td>
</tr>
<tr>
<td>6</td>
<td><strong>ToDouble</strong>把类型转换为双精度浮点型。</td>
</tr>
<tr>
<td>7</td>
<td><strong>ToInt16</strong>把类型转换为 16 位整数类型。</td>
</tr>
<tr>
<td>8</td>
<td><strong>ToInt32</strong>把类型转换为 32 位整数类型。</td>
</tr>
<tr>
<td>9</td>
<td><strong>ToInt64</strong>把类型转换为 64 位整数类型。</td>
</tr>
<tr>
<td>10</td>
<td><strong>ToSbyte</strong>把类型转换为有符号字节类型。</td>
</tr>
<tr>
<td>11</td>
<td><strong>ToSingle</strong>把类型转换为小浮点数类型。</td>
</tr>
<tr>
<td>12</td>
<td><strong>ToString</strong>把类型转换为字符串类型。</td>
</tr>
<tr>
<td>13</td>
<td><strong>ToType</strong>把类型转换为指定类型。</td>
</tr>
<tr>
<td>14</td>
<td><strong>ToUInt16</strong>把类型转换为 16 位无符号整数类型。</td>
</tr>
<tr>
<td>15</td>
<td><strong>ToUInt32</strong>把类型转换为 32 位无符号整数类型。</td>
</tr>
<tr>
<td>16</td>
<td><strong>ToUInt64</strong>把类型转换为 64 位无符号整数类型。</td>
</tr>
</tbody>
</table>
<p>下面的实例把不同值的类型转换为字符串类型：</p>
<p><code>实例</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">namespace TypeConversionApplication</span><br><span class="line">&#123;</span><br><span class="line">    class StringConversion</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            int i = 75;</span><br><span class="line">            float f = 53.005f;</span><br><span class="line">            double d = 2345.7652;</span><br><span class="line">            bool b = true;</span><br><span class="line">            Console.WriteLine(i.ToString());</span><br><span class="line">            Console.WriteLine(f.ToString());</span><br><span class="line">            Console.WriteLine(d.ToString());</span><br><span class="line">            Console.WriteLine(b.ToString());</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>当上面的代码被编译和执行时，它会产生下列结果：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">75</span><br><span class="line">53.005</span><br><span class="line">2345.7652</span><br><span class="line">True</span><br></pre></td></tr></table></figure>
<h2 id="七-C-变量"><a href="#七-C-变量" class="headerlink" title="七.C# 变量"></a>七.C# 变量</h2><p>一个变量只不过是一个供程序操作的存储区的名字。在 C# 中，每个变量都有一个特定的类型，类型决定了变量的内存大小和布局。范围内的值可以存储在内存中，可以对变量进行一系列操作。</p>
<p>我们已经讨论了各种数据类型。C# 中提供的基本的值类型大致可以分为以下几类：</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>举例</th>
</tr>
</thead>
<tbody>
<tr>
<td>整数类型</td>
<td>sbyte、byte、short、ushort、int、uint、long、ulong 和 char</td>
</tr>
<tr>
<td>浮点型</td>
<td>float 和 double</td>
</tr>
<tr>
<td>十进制类型</td>
<td>decimal</td>
</tr>
<tr>
<td>布尔类型</td>
<td>true 或 false 值，指定的值</td>
</tr>
<tr>
<td>空类型</td>
<td>可为空值的数据类型</td>
</tr>
</tbody>
</table>
<p>C# 允许定义其他值类型的变量，比如 <strong>enum</strong>，也允许定义引用类型变量，比如 <strong>class</strong>。这些我们将在以后的章节中进行讨论。在本章节中，我们只研究基本变量类型。</p>
<h3 id="1-C-中的变量定义"><a href="#1-C-中的变量定义" class="headerlink" title="1.C# 中的变量定义"></a><strong>1.C# 中的变量定义</strong></h3><p>C# 中变量定义的语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;data_type&gt; &lt;variable_list&gt;;</span><br></pre></td></tr></table></figure>
<p>在这里，data_type 必须是一个有效的 C# 数据类型，可以是 char、int、float、double 或其他用户自定义的数据类型。variable_list 可以由一个或多个用逗号分隔的标识符名称组成。</p>
<p>一些有效的变量定义如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">int i, j, k;</span><br><span class="line">char c, ch;</span><br><span class="line">float f, salary;</span><br><span class="line">double d;</span><br></pre></td></tr></table></figure>
<p>您可以在变量定义时进行初始化：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int i = 100;</span><br></pre></td></tr></table></figure>
<h3 id="2-C-中的变量初始化"><a href="#2-C-中的变量初始化" class="headerlink" title="2.C# 中的变量初始化"></a><strong>2.C# 中的变量初始化</strong></h3><p>变量通过在等号后跟一个常量表达式进行初始化（赋值）。初始化的一般形式为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">variable_name = value;</span><br></pre></td></tr></table></figure>
<p>变量可以在声明时被初始化（指定一个初始值）。初始化由一个等号后跟一个常量表达式组成，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;data_type&gt; &lt;variable_name&gt; = value;</span><br></pre></td></tr></table></figure>
<p>一些实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">int d = 3, f = 5;    /* 初始化 d 和 f. */</span><br><span class="line">byte z = 22;         /* 初始化 z. */</span><br><span class="line">double pi = 3.14159; /* 声明 pi 的近似值 */</span><br><span class="line">char x = &apos;x&apos;;        /* 变量 x 的值为 &apos;x&apos; */</span><br></pre></td></tr></table></figure>
<p>正确地初始化变量是一个良好的编程习惯，否则有时程序会产生意想不到的结果。</p>
<p>请看下面的实例，使用了各种类型的变量：</p>
<p><code>实例</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">namespace VariableDefinition</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            short a;</span><br><span class="line">            int b ;</span><br><span class="line">            double c;</span><br><span class="line">            /* 实际初始化 */</span><br><span class="line">            a = 10;</span><br><span class="line">            b = 20;</span><br><span class="line">            c = a + b;</span><br><span class="line">            Console.WriteLine(&quot;a = &#123;0&#125;, b = &#123;1&#125;, c = &#123;2&#125;&quot;, a, b, c);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a = 10, b = 20, c = 30</span><br></pre></td></tr></table></figure>
<h3 id="3-接受来自用户的值"><a href="#3-接受来自用户的值" class="headerlink" title="3.接受来自用户的值"></a><strong>3.接受来自用户的值</strong></h3><p>System命名空间中的 Console类提供了一个函数 ReadLine()，用于接收来自用户的输入，并把它存储到一个变量中。</p>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int num;</span><br><span class="line">num = Convert.ToInt32(Console.ReadLine());</span><br></pre></td></tr></table></figure>
<p>函数 <strong>Convert.ToInt32()</strong> 把用户输入的数据转换为 int 数据类型，因为 <strong>Console.ReadLine()</strong> 只接受字符串格式的数据。</p>
<h3 id="4-C-中的-Lvalues-和-Rvalues"><a href="#4-C-中的-Lvalues-和-Rvalues" class="headerlink" title="4.C# 中的 Lvalues 和 Rvalues"></a><strong>4.C# 中的 Lvalues 和 Rvalues</strong></h3><p>C# 中的两种表达式：</p>
<ol>
<li><strong>lvalue</strong>：lvalue 表达式可以出现在赋值语句的左边或右边。</li>
<li><strong>rvalue</strong>：rvalue 表达式可以出现在赋值语句的右边，不能出现在赋值语句的左边。</li>
</ol>
<p>变量是 lvalue 的，所以可以出现在赋值语句的左边。数值是 rvalue 的，因此不能被赋值，不能出现在赋值语句的左边。下面是一个有效的语句：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int g = 20;</span><br></pre></td></tr></table></figure>
<p>下面是一个无效的语句，会产生编译时错误：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">10 = 20;</span><br></pre></td></tr></table></figure>
<h2 id="八-C-常量"><a href="#八-C-常量" class="headerlink" title="八.C# 常量"></a>八.C# 常量</h2><p>常量是固定值，程序执行期间不会改变。常量可以是任何基本数据类型，比如整数常量、浮点常量、字符常量或者字符串常量，还有枚举常量。</p>
<p>常量可以被当作常规的变量，只是它们的值在定义后不能被修改。</p>
<h3 id="1-整数常量"><a href="#1-整数常量" class="headerlink" title="1.整数常量"></a><strong>1.整数常量</strong></h3><p>整数常量可以是十进制、八进制或十六进制的常量。前缀指定基数：0x 或 0X 表示十六进制，0 表示八进制，没有前缀则表示十进制。</p>
<p>整数常量也可以有后缀，可以是 U 和 L 的组合，其中，U 和 L 分别表示 unsigned 和 long。后缀可以是大写或者小写，多个后缀以任意顺序进行组合。</p>
<p>这里有一些整数常量的实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">212         /* 合法 */</span><br><span class="line">215u        /* 合法 */</span><br><span class="line">0xFeeL      /* 合法 */</span><br><span class="line">078         /* 非法：8 不是一个八进制数字 */</span><br><span class="line">032UU       /* 非法：不能重复后缀 */</span><br></pre></td></tr></table></figure>
<p>以下是各种类型的整数常量的实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">85         /* 十进制 */</span><br><span class="line">0213       /* 八进制 */</span><br><span class="line">0x4b       /* 十六进制 */</span><br><span class="line">30         /* int */</span><br><span class="line">30u        /* 无符号 int */</span><br><span class="line">30l        /* long */</span><br><span class="line">30ul       /* 无符号 long */</span><br></pre></td></tr></table></figure>
<h3 id="2-浮点常量"><a href="#2-浮点常量" class="headerlink" title="2.浮点常量"></a><strong>2.浮点常量</strong></h3><p>一个浮点常量是由整数部分、小数点、小数部分和指数部分组成。您可以使用小数形式或者指数形式来表示浮点常量。</p>
<p>这里有一些浮点常量的实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">3.14159       /* 合法 */</span><br><span class="line">314159E-5L    /* 合法 */</span><br><span class="line">510E          /* 非法：不完全指数 */</span><br><span class="line">210f          /* 非法：没有小数或指数 */</span><br><span class="line">.e55          /* 非法：缺少整数或小数 */</span><br></pre></td></tr></table></figure>
<p>使用小数形式表示时，必须包含小数点、指数或同时包含两者。使用指数形式表示时，必须包含整数部分、小数部分或同时包含两者。有符号的指数是用 e 或 E 表示的。</p>
<h3 id="3-字符常量"><a href="#3-字符常量" class="headerlink" title="3.字符常量"></a><strong>3.字符常量</strong></h3><p>字符常量是括在单引号里，例如，’x’，且可存储在一个简单的字符类型变量中。一个字符常量可以是一个普通字符（例如 ‘x’）、一个转义序列（例如 ‘\t’）或者一个通用字符（例如 ‘\u02C0’）。</p>
<p>在 C# 中有一些特定的字符，当它们的前面带有反斜杠时有特殊的意义，可用于表示换行符（\n）或制表符 tab（\t）。在这里，列出一些转义序列码：</p>
<table>
<thead>
<tr>
<th>转义序列</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>\</td>
<td>\ 字符</td>
</tr>
<tr>
<td>\’</td>
<td>‘ 字符</td>
</tr>
<tr>
<td>\”</td>
<td>“ 字符</td>
</tr>
<tr>
<td>\?</td>
<td>? 字符</td>
</tr>
<tr>
<td>\a</td>
<td>Alert 或 bell</td>
</tr>
<tr>
<td>\b</td>
<td>退格键（Backspace）</td>
</tr>
<tr>
<td>\f</td>
<td>换页符（Form feed）</td>
</tr>
<tr>
<td>\n</td>
<td>换行符（Newline）</td>
</tr>
<tr>
<td>\r</td>
<td>回车</td>
</tr>
<tr>
<td>\t</td>
<td>水平制表符 tab</td>
</tr>
<tr>
<td>\v</td>
<td>垂直制表符 tab</td>
</tr>
<tr>
<td>\ooo</td>
<td>一到三位的八进制数</td>
</tr>
<tr>
<td>\xhh . . .</td>
<td>一个或多个数字的十六进制数</td>
</tr>
</tbody>
</table>
<p>以下是一些转义序列字符的实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">namespace EscapeChar</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;Hello\tWorld\n\n&quot;);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Hello   World</span><br></pre></td></tr></table></figure>
<h3 id="4-字符串常量"><a href="#4-字符串常量" class="headerlink" title="4.字符串常量"></a><strong>4.字符串常量</strong></h3><p>字符串常量是括在双引号 “” 里，或者是括在 @”” 里。字符串常量包含的字符与字符常量相似，可以是：普通字符、转义序列和通用字符</p>
<p>使用字符串常量时，可以把一个很长的行拆成多个行，可以使用空格分隔各个部分。</p>
<p>这里是一些字符串常量的实例。下面所列的各种形式表示相同的字符串。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">string a = &quot;hello, world&quot;;                  // hello, world</span><br><span class="line">string b = @&quot;hello, world&quot;;               // hello, world</span><br><span class="line">string c = &quot;hello \t world&quot;;               // hello     world</span><br><span class="line">string d = @&quot;hello \t world&quot;;               // hello \t world</span><br><span class="line">string e = &quot;Joe said \&quot;Hello\&quot; to me&quot;;      // Joe said &quot;Hello&quot; to me</span><br><span class="line">string f = @&quot;Joe said &quot;&quot;Hello&quot;&quot; to me&quot;;   // Joe said &quot;Hello&quot; to me</span><br><span class="line">string g = &quot;\\\\server\\share\\file.txt&quot;;   // \\server\share\file.txt</span><br><span class="line">string h = @&quot;\\server\share\file.txt&quot;;      // \\server\share\file.txt</span><br><span class="line">string i = &quot;one\r\ntwo\r\nthree&quot;;</span><br><span class="line">string j = @&quot;one</span><br><span class="line">two</span><br><span class="line">three&quot;;</span><br></pre></td></tr></table></figure>
<h3 id="5-定义常量"><a href="#5-定义常量" class="headerlink" title="5.定义常量"></a><strong>5.定义常量</strong></h3><p>常量是使用 <strong>const</strong> 关键字来定义的 。定义一个常量的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">const &lt;data_type&gt; &lt;constant_name&gt; = value;</span><br></pre></td></tr></table></figure>
<p>下面的代码演示了如何在程序中定义和使用常量：</p>
<h3 id="6-实例"><a href="#6-实例" class="headerlink" title="6.实例"></a><strong>6.实例</strong></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">public class ConstTest </span><br><span class="line">&#123;</span><br><span class="line">    class SampleClass</span><br><span class="line">    &#123;</span><br><span class="line">        public int x;</span><br><span class="line">        public int y;</span><br><span class="line">        public const int c1 = 5;</span><br><span class="line">        public const int c2 = c1 + 5;</span><br><span class="line">        public SampleClass(int p1, int p2) </span><br><span class="line">        &#123;</span><br><span class="line">            x = p1; </span><br><span class="line">            y = p2;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    static void Main()</span><br><span class="line">    &#123;</span><br><span class="line">        SampleClass mC = new SampleClass(11, 22);</span><br><span class="line">        Console.WriteLine(&quot;x = &#123;0&#125;, y = &#123;1&#125;&quot;, mC.x, mC.y);</span><br><span class="line">        Console.WriteLine(&quot;c1 = &#123;0&#125;, c2 = &#123;1&#125;&quot;, </span><br><span class="line">                          SampleClass.c1, SampleClass.c2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">x = 11, y = 22</span><br><span class="line">c1 = 5, c2 = 10</span><br></pre></td></tr></table></figure>
<h2 id="九-C-运算符"><a href="#九-C-运算符" class="headerlink" title="九.C# 运算符"></a>九.C# 运算符</h2><p>运算符是一种告诉编译器执行特定的数学或逻辑操作的符号。C# 有丰富的内置运算符，分类如下：</p>
<ul>
<li>算术运算符</li>
<li>关系运算符</li>
<li>逻辑运算符</li>
<li>位运算符</li>
<li>赋值运算符</li>
<li>其他运算符</li>
</ul>
<p>本教程将逐一讲解算术运算符、关系运算符、逻辑运算符、位运算符、赋值运算符及其他运算符。</p>
<h3 id="1-算术运算符"><a href="#1-算术运算符" class="headerlink" title="1.算术运算符"></a><strong>1.算术运算符</strong></h3><p>下表显示了 C# 支持的所有算术运算符。假设变量 <strong>A</strong> 的值为 10，变量 <strong>B</strong> 的值为 20，则：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>+</td>
<td>把两个操作数相加</td>
<td>A + B 将得到 30</td>
</tr>
<tr>
<td>-</td>
<td>从第一个操作数中减去第二个操作数</td>
<td>A - B 将得到 -10</td>
</tr>
<tr>
<td>*</td>
<td>把两个操作数相乘</td>
<td>A * B 将得到 200</td>
</tr>
<tr>
<td>/</td>
<td>分子除以分母</td>
<td>B / A 将得到 2</td>
</tr>
<tr>
<td>%</td>
<td>取模运算符，整除后的余数</td>
<td>B % A 将得到 0</td>
</tr>
<tr>
<td>++</td>
<td>自增运算符，整数值增加 1</td>
<td>A++ 将得到 11</td>
</tr>
<tr>
<td>–</td>
<td>自减运算符，整数值减少 1</td>
<td>A– 将得到 9</td>
</tr>
</tbody>
</table>
<p>请看下面的实例，了解 C# 中所有可用的算术运算符：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            int a = 21;</span><br><span class="line">            int b = 10;</span><br><span class="line">            int c;</span><br><span class="line">            c = a + b;</span><br><span class="line">            Console.WriteLine(&quot;Line 1 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            c = a - b;</span><br><span class="line">            Console.WriteLine(&quot;Line 2 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            c = a * b;</span><br><span class="line">            Console.WriteLine(&quot;Line 3 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            c = a / b;</span><br><span class="line">            Console.WriteLine(&quot;Line 4 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            c = a % b;</span><br><span class="line">            Console.WriteLine(&quot;Line 5 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            // ++a 先进行自增运算再赋值</span><br><span class="line">            c = ++a;</span><br><span class="line">            Console.WriteLine(&quot;Line 6 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            // 此时 a 的值为 22</span><br><span class="line">            // --a 先进行自减运算再赋值</span><br><span class="line">            c = --a;</span><br><span class="line">            Console.WriteLine(&quot;Line 7 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Line 1 - c 的值是 31</span><br><span class="line">Line 2 - c 的值是 11</span><br><span class="line">Line 3 - c 的值是 210</span><br><span class="line">Line 4 - c 的值是 2</span><br><span class="line">Line 5 - c 的值是 1</span><br><span class="line">Line 6 - c 的值是 22</span><br><span class="line">Line 7 - c 的值是 21</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>c = a++</strong>: 先将 a 赋值给 c，再对 a 进行自增运算。</li>
<li><strong>c = ++a</strong>: 先将 a 进行自增运算，再将 a 赋值给 c 。</li>
<li><strong>c = a–</strong>: 先将 a 赋值给 c，再对 a 进行自减运算。</li>
<li><strong>c = –a</strong>: 先将 a 进行自减运算，再将 a 赋值给 c 。</li>
</ul>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            int a = 1;</span><br><span class="line">            int b;</span><br><span class="line">            // a++ 先赋值再进行自增运算</span><br><span class="line">            b = a++;</span><br><span class="line">            Console.WriteLine(&quot;a = &#123;0&#125;&quot;, a);</span><br><span class="line">            Console.WriteLine(&quot;b = &#123;0&#125;&quot;, b);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">            // ++a 先进行自增运算再赋值</span><br><span class="line">            a = 1; // 重新初始化 a</span><br><span class="line">            b = ++a;</span><br><span class="line">            Console.WriteLine(&quot;a = &#123;0&#125;&quot;, a);</span><br><span class="line">            Console.WriteLine(&quot;b = &#123;0&#125;&quot;, b);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">            // a-- 先赋值再进行自减运算</span><br><span class="line">            a = 1;  // 重新初始化 a</span><br><span class="line">            b= a--;</span><br><span class="line">            Console.WriteLine(&quot;a = &#123;0&#125;&quot;, a);</span><br><span class="line">            Console.WriteLine(&quot;b = &#123;0&#125;&quot;, b);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">            // --a 先进行自减运算再赋值</span><br><span class="line">            a = 1;  // 重新初始化 a</span><br><span class="line">            b= --a;</span><br><span class="line">            Console.WriteLine(&quot;a = &#123;0&#125;&quot;, a);</span><br><span class="line">            Console.WriteLine(&quot;b = &#123;0&#125;&quot;, b);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行实例 »</p>
<p>执行以上程序，输出结果为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">a = 2</span><br><span class="line">b = 1</span><br><span class="line">a = 2</span><br><span class="line">b = 2</span><br><span class="line">a = 0</span><br><span class="line">b = 1</span><br><span class="line">a = 0</span><br><span class="line">b = 0</span><br></pre></td></tr></table></figure>
<h3 id="2-关系运算符"><a href="#2-关系运算符" class="headerlink" title="2. 关系运算符"></a><strong>2. 关系运算符</strong></h3><p>下表显示了 C# 支持的所有关系运算符。假设变量 <strong>A</strong> 的值为 10，变量 <strong>B</strong> 的值为 20，则：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>==</td>
<td>检查两个操作数的值是否相等，如果相等则条件为真。</td>
<td>(A == B) 不为真。</td>
</tr>
<tr>
<td>!=</td>
<td>检查两个操作数的值是否相等，如果不相等则条件为真。</td>
<td>(A != B) 为真。</td>
</tr>
<tr>
<td>&gt;</td>
<td>检查左操作数的值是否大于右操作数的值，如果是则条件为真。</td>
<td>(A &gt; B) 不为真。</td>
</tr>
<tr>
<td>&lt;</td>
<td>检查左操作数的值是否小于右操作数的值，如果是则条件为真。</td>
<td>(A &lt; B) 为真。</td>
</tr>
<tr>
<td>&gt;=</td>
<td>检查左操作数的值是否大于或等于右操作数的值，如果是则条件为真。</td>
<td>(A &gt;= B) 不为真。</td>
</tr>
<tr>
<td>&lt;=</td>
<td>检查左操作数的值是否小于或等于右操作数的值，如果是则条件为真。</td>
<td>(A &lt;= B) 为真。</td>
</tr>
</tbody>
</table>
<p>请看下面的实例，了解 C# 中所有可用的关系运算符：</p>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">class Program</span><br><span class="line">&#123;</span><br><span class="line">  static void Main(string[] args)</span><br><span class="line">  &#123;</span><br><span class="line">      int a = 21;</span><br><span class="line">      int b = 10;</span><br><span class="line">      if (a == b)</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;Line 1 - a 等于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      else</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;Line 1 - a 不等于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      if (a &lt; b)</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;Line 2 - a 小于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      else</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;Line 2 - a 不小于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      if (a &gt; b)</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;Line 3 - a 大于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      else</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;Line 3 - a 不大于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      /* 改变 a 和 b 的值 */</span><br><span class="line">      a = 5;</span><br><span class="line">      b = 20;</span><br><span class="line">      if (a &lt;= b)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Line 4 - a 小于或等于 b&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      if (b &gt;= a)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Line 5 - b 大于或等于 a&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Line 1 - a 不等于 b</span><br><span class="line">Line 2 - a 不小于 b</span><br><span class="line">Line 3 - a 大于 b</span><br><span class="line">Line 4 - a 小于或等于 b</span><br><span class="line">Line 5 - b 大于或等于 a</span><br></pre></td></tr></table></figure>
<h3 id="3-逻辑运算符"><a href="#3-逻辑运算符" class="headerlink" title="3. 逻辑运算符"></a><strong>3. 逻辑运算符</strong></h3><p>下表显示了 C# 支持的所有逻辑运算符。假设变量 <strong>A</strong> 为布尔值 true，变量 <strong>B</strong> 为布尔值 false，则：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>&amp;&amp;</td>
<td>称为逻辑与运算符。如果两个操作数都非零，则条件为真。</td>
<td>(A &amp;&amp; B) 为假。</td>
</tr>
<tr>
<td>\</td>
<td>\</td>
<td></td>
<td>称为逻辑或运算符。如果两个操作数中有任意一个非零，则条件为真。</td>
<td>(A \</td>
<td>\</td>
<td>B) 为真。</td>
</tr>
<tr>
<td>!</td>
<td>称为逻辑非运算符。用来逆转操作数的逻辑状态。如果条件为真则逻辑非运算符将使其为假。</td>
<td>!(A &amp;&amp; B) 为真。</td>
</tr>
</tbody>
</table>
<p>请看下面的实例，了解 C# 中所有可用的逻辑运算符：</p>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            bool a = true;</span><br><span class="line">            bool b = true;</span><br><span class="line">            if (a &amp;&amp; b)</span><br><span class="line">            &#123;</span><br><span class="line">               Console.WriteLine(&quot;Line 1 - 条件为真&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            if (a || b)</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Line 2 - 条件为真&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            /* 改变 a 和 b 的值 */</span><br><span class="line">            a = false;</span><br><span class="line">            b = true;</span><br><span class="line">            if (a &amp;&amp; b)</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Line 3 - 条件为真&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            else</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Line 3 - 条件不为真&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            if (!(a &amp;&amp; b))</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Line 4 - 条件为真&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Line 1 - 条件为真</span><br><span class="line">Line 2 - 条件为真</span><br><span class="line">Line 3 - 条件不为真</span><br><span class="line">Line 4 - 条件为真</span><br></pre></td></tr></table></figure>
<h3 id="4-位运算符"><a href="#4-位运算符" class="headerlink" title="4.位运算符"></a><strong>4.位运算符</strong></h3><p>位运算符作用于位，并逐位执行操作。&amp;、 | 和 ^ 的真值表如下所示：</p>
<table>
<thead>
<tr>
<th>p</th>
<th>q</th>
<th>p &amp; q</th>
<th>p \</th>
<th>q</th>
<th>p ^ q</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
<p>假设如果 A = 60，且 B = 13，现在以二进制格式表示，它们如下所示：</p>
<p>A = 0011 1100</p>
<p>B = 0000 1101</p>
<p>-—————-</p>
<p>A&amp;B = 0000 1100</p>
<p>A|B = 0011 1101</p>
<p>A^B = 0011 0001</p>
<p>~A  = 1100 0011</p>
<p>下表列出了 C# 支持的位运算符。假设变量 <strong>A</strong> 的值为 60，变量 <strong>B</strong> 的值为 13，则：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>&amp;</td>
<td>如果同时存在于两个操作数中，二进制 AND 运算符复制一位到结果中。</td>
<td>(A &amp; B) 将得到 12，即为 0000 1100</td>
</tr>
<tr>
<td>\</td>
<td></td>
<td>如果存在于任一操作数中，二进制 OR 运算符复制一位到结果中。</td>
<td>(A \</td>
<td>B) 将得到 61，即为 0011 1101</td>
</tr>
<tr>
<td>^</td>
<td>如果存在于其中一个操作数中但不同时存在于两个操作数中，二进制异或运算符复制一位到结果中。</td>
<td>(A ^ B) 将得到 49，即为 0011 0001</td>
</tr>
<tr>
<td>~</td>
<td>按位取反运算符是一元运算符，具有”翻转”位效果，即0变成1，1变成0，包括符号位。</td>
<td>(~A ) 将得到 -61，即为 1100 0011，一个有符号二进制数的补码形式。</td>
</tr>
<tr>
<td>&lt;&lt;</td>
<td>二进制左移运算符。左操作数的值向左移动右操作数指定的位数。</td>
<td>A &lt;&lt; 2 将得到 240，即为 1111 0000</td>
</tr>
<tr>
<td>&gt;&gt;</td>
<td>二进制右移运算符。左操作数的值向右移动右操作数指定的位数。</td>
<td>A &gt;&gt; 2 将得到 15，即为 0000 1111</td>
</tr>
</tbody>
</table>
<p>请看下面的实例，了解 C# 中所有可用的位运算符：</p>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            int a = 60;            /* 60 = 0011 1100 */  </span><br><span class="line">            int b = 13;            /* 13 = 0000 1101 */</span><br><span class="line">            int c = 0;           </span><br><span class="line">             c = a &amp; b;           /* 12 = 0000 1100 */ </span><br><span class="line">             Console.WriteLine(&quot;Line 1 - c 的值是 &#123;0&#125;&quot;, c );</span><br><span class="line">             c = a | b;           /* 61 = 0011 1101 */</span><br><span class="line">             Console.WriteLine(&quot;Line 2 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">             c = a ^ b;           /* 49 = 0011 0001 */</span><br><span class="line">             Console.WriteLine(&quot;Line 3 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">             c = ~a;               /*-61 = 1100 0011 */</span><br><span class="line">             Console.WriteLine(&quot;Line 4 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">             c = a &lt;&lt; 2;     /* 240 = 1111 0000 */</span><br><span class="line">             Console.WriteLine(&quot;Line 5 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">             c = a &gt;&gt; 2;     /* 15 = 0000 1111 */</span><br><span class="line">             Console.WriteLine(&quot;Line 6 - c 的值是 &#123;0&#125;&quot;, c);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Line 1 - c 的值是 12</span><br><span class="line">Line 2 - c 的值是 61</span><br><span class="line">Line 3 - c 的值是 49</span><br><span class="line">Line 4 - c 的值是 -61</span><br><span class="line">Line 5 - c 的值是 240</span><br><span class="line">Line 6 - c 的值是 15</span><br></pre></td></tr></table></figure>
<h3 id="5-赋值运算符"><a href="#5-赋值运算符" class="headerlink" title="5.赋值运算符"></a><strong>5.赋值运算符</strong></h3><p>下表列出了 C# 支持的赋值运算符：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>=</td>
<td>简单的赋值运算符，把右边操作数的值赋给左边操作数</td>
<td>C = A + B 将把 A + B 的值赋给 C</td>
</tr>
<tr>
<td>+=</td>
<td>加且赋值运算符，把右边操作数加上左边操作数的结果赋值给左边操作数</td>
<td>C += A 相当于 C = C + A</td>
</tr>
<tr>
<td>-=</td>
<td>减且赋值运算符，把左边操作数减去右边操作数的结果赋值给左边操作数</td>
<td>C -= A 相当于 C = C - A</td>
</tr>
<tr>
<td>*=</td>
<td>乘且赋值运算符，把右边操作数乘以左边操作数的结果赋值给左边操作数</td>
<td>C <em>= A 相当于 C = C </em> A</td>
</tr>
<tr>
<td>/=</td>
<td>除且赋值运算符，把左边操作数除以右边操作数的结果赋值给左边操作数</td>
<td>C /= A 相当于 C = C / A</td>
</tr>
<tr>
<td>%=</td>
<td>求模且赋值运算符，求两个操作数的模赋值给左边操作数</td>
<td>C %= A 相当于 C = C % A</td>
</tr>
<tr>
<td>&lt;&lt;=</td>
<td>左移且赋值运算符</td>
<td>C &lt;&lt;= 2 等同于 C = C &lt;&lt; 2</td>
</tr>
<tr>
<td>&gt;&gt;=</td>
<td>右移且赋值运算符</td>
<td>C &gt;&gt;= 2 等同于 C = C &gt;&gt; 2</td>
</tr>
<tr>
<td>&amp;=</td>
<td>按位与且赋值运算符</td>
<td>C &amp;= 2 等同于 C = C &amp; 2</td>
</tr>
<tr>
<td>^=</td>
<td>按位异或且赋值运算符</td>
<td>C ^= 2 等同于 C = C ^ 2</td>
</tr>
<tr>
<td>\</td>
<td>=</td>
<td>按位或且赋值运算符</td>
<td>C \</td>
<td>= 2 等同于 C = C \</td>
<td>2</td>
</tr>
</tbody>
</table>
<p>请看下面的实例，了解 C# 中所有可用的赋值运算符：</p>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            int a = 21;</span><br><span class="line">            int c;</span><br><span class="line">            c = a;</span><br><span class="line">            Console.WriteLine(&quot;Line 1 - =  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c += a;</span><br><span class="line">            Console.WriteLine(&quot;Line 2 - += c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c -= a;</span><br><span class="line">            Console.WriteLine(&quot;Line 3 - -=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c *= a;</span><br><span class="line">            Console.WriteLine(&quot;Line 4 - *=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c /= a;</span><br><span class="line">            Console.WriteLine(&quot;Line 5 - /=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c = 200;</span><br><span class="line">            c %= a;</span><br><span class="line">            Console.WriteLine(&quot;Line 6 - %=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c &lt;&lt;= 2;</span><br><span class="line">            Console.WriteLine(&quot;Line 7 - &lt;&lt;=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c &gt;&gt;= 2;</span><br><span class="line">            Console.WriteLine(&quot;Line 8 - &gt;&gt;=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c &amp;= 2;</span><br><span class="line">            Console.WriteLine(&quot;Line 9 - &amp;=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c ^= 2;</span><br><span class="line">            Console.WriteLine(&quot;Line 10 - ^=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            c |= 2;</span><br><span class="line">            Console.WriteLine(&quot;Line 11 - |=  c 的值 = &#123;0&#125;&quot;, c);</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Line 1 - =     c 的值 = 21</span><br><span class="line">Line 2 - +=    c 的值 = 42</span><br><span class="line">Line 3 - -=    c 的值 = 21</span><br><span class="line">Line 4 - *=    c 的值 = 441</span><br><span class="line">Line 5 - /=    c 的值 = 21</span><br><span class="line">Line 6 - %=    c 的值 = 11</span><br><span class="line">Line 7 - &lt;&lt;=    c 的值 = 44</span><br><span class="line">Line 8 - &gt;&gt;=    c 的值 = 11</span><br><span class="line">Line 9 - &amp;=    c 的值 = 2</span><br><span class="line">Line 10 - ^=    c 的值 = 0</span><br><span class="line">Line 11 - |=    c 的值 = 2</span><br></pre></td></tr></table></figure>
<h3 id="6-其他运算符"><a href="#6-其他运算符" class="headerlink" title="6.其他运算符"></a><strong>6.其他运算符</strong></h3><p>下表列出了 C# 支持的其他一些重要的运算符，包括 <strong>sizeof</strong>、<strong>typeof</strong> 和 <strong>? :</strong>。</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>sizeof()</td>
<td>返回数据类型的大小。</td>
<td>sizeof(int)，将返回 4.</td>
</tr>
<tr>
<td>typeof()</td>
<td>返回 class 的类型。</td>
<td>typeof(StreamReader);</td>
</tr>
<tr>
<td>&amp;</td>
<td>返回变量的地址。</td>
<td>&a; 将得到变量的实际地址。</td>
</tr>
<tr>
<td>*</td>
<td>变量的指针。</td>
<td>*a; 将指向一个变量。</td>
</tr>
<tr>
<td>? :</td>
<td>条件表达式</td>
<td>如果条件为真 ? 则为 X : 否则为 Y</td>
</tr>
<tr>
<td>is</td>
<td>判断对象是否为某一类型。</td>
<td>If( Ford is Car) // 检查 Ford 是否是 Car 类的一个对象。</td>
</tr>
<tr>
<td>as</td>
<td>强制转换，即使转换失败也不会抛出异常。</td>
<td>Object obj = new StringReader(“Hello”);StringReader r = obj as StringReader;</td>
</tr>
</tbody>
</table>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         /* sizeof 运算符的实例 */</span><br><span class="line">         Console.WriteLine(&quot;int 的大小是 &#123;0&#125;&quot;, sizeof(int));</span><br><span class="line">         Console.WriteLine(&quot;short 的大小是 &#123;0&#125;&quot;, sizeof(short));</span><br><span class="line">         Console.WriteLine(&quot;double 的大小是 &#123;0&#125;&quot;, sizeof(double));</span><br><span class="line">         /* 三元运算符的实例 */</span><br><span class="line">         int a, b;</span><br><span class="line">         a = 10;</span><br><span class="line">         b = (a == 1) ? 20 : 30;</span><br><span class="line">         Console.WriteLine(&quot;b 的值是 &#123;0&#125;&quot;, b);</span><br><span class="line">         b = (a == 10) ? 20 : 30;</span><br><span class="line">         Console.WriteLine(&quot;b 的值是 &#123;0&#125;&quot;, b);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">int 的大小是 4</span><br><span class="line">short 的大小是 2</span><br><span class="line">double 的大小是 8</span><br><span class="line">b 的值是 30</span><br><span class="line">b 的值是 20</span><br></pre></td></tr></table></figure>
<h3 id="7-C-中的运算符优先级"><a href="#7-C-中的运算符优先级" class="headerlink" title="7.C# 中的运算符优先级"></a><strong>7.C# 中的运算符优先级</strong></h3><p>运算符的优先级确定表达式中项的组合。这会影响到一个表达式如何计算。某些运算符比其他运算符有更高的优先级，例如，乘除运算符具有比加减运算符更高的优先级。</p>
<p>例如 x = 7 + 3 <em> 2，在这里，x 被赋值为 13，而不是 20，因为运算符 </em> 具有比 + 更高的优先级，所以首先计算乘法 3*2，然后再加上 7。</p>
<p>下表将按运算符优先级从高到低列出各个运算符，具有较高优先级的运算符出现在表格的上面，具有较低优先级的运算符出现在表格的下面。在表达式中，较高优先级的运算符会优先被计算。</p>
<table>
<thead>
<tr>
<th>类别</th>
<th>运算符</th>
<th>结合性</th>
</tr>
</thead>
<tbody>
<tr>
<td>后缀</td>
<td>() [] -&gt; . ++ - -</td>
<td>从左到右</td>
</tr>
<tr>
<td>一元</td>
<td>+ - ! ~ ++ - - (type)* &amp; sizeof</td>
<td>从右到左</td>
</tr>
<tr>
<td>乘除</td>
<td>* / %</td>
<td>从左到右</td>
</tr>
<tr>
<td>加减</td>
<td>+ -</td>
<td>从左到右</td>
</tr>
<tr>
<td>移位</td>
<td>&lt;&lt; &gt;&gt;</td>
<td>从左到右</td>
</tr>
<tr>
<td>关系</td>
<td>&lt; &lt;= &gt; &gt;=</td>
<td>从左到右</td>
</tr>
<tr>
<td>相等</td>
<td>== !=</td>
<td>从左到右</td>
</tr>
<tr>
<td>位与 AND</td>
<td>&amp;</td>
<td>从左到右</td>
</tr>
<tr>
<td>位异或 XOR</td>
<td>^</td>
<td>从左到右</td>
</tr>
<tr>
<td>位或 OR</td>
<td>\</td>
<td></td>
<td>从左到右</td>
</tr>
<tr>
<td>逻辑与 AND</td>
<td>&amp;&amp;</td>
<td>从左到右</td>
</tr>
<tr>
<td>逻辑或 OR</td>
<td>\</td>
<td>\</td>
<td></td>
<td>从左到右</td>
</tr>
<tr>
<td>条件</td>
<td>?:</td>
<td>从右到左</td>
</tr>
<tr>
<td>赋值</td>
<td>= += -= *= /= %=&gt;&gt;= &lt;&lt;= &amp;= ^= \</td>
<td>=</td>
<td>从右到左</td>
</tr>
<tr>
<td>逗号</td>
<td>,</td>
<td>从左到右</td>
</tr>
</tbody>
</table>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorsAppl</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         int a = 20;</span><br><span class="line">         int b = 10;</span><br><span class="line">         int c = 15;</span><br><span class="line">         int d = 5;</span><br><span class="line">         int e;</span><br><span class="line">         e = (a + b) * c / d;     // ( 30 * 15 ) / 5</span><br><span class="line">         Console.WriteLine(&quot;(a + b) * c / d 的值是 &#123;0&#125;&quot;, e);</span><br><span class="line">         e = ((a + b) * c) / d;   // (30 * 15 ) / 5</span><br><span class="line">         Console.WriteLine(&quot;((a + b) * c) / d 的值是 &#123;0&#125;&quot;, e);</span><br><span class="line">         e = (a + b) * (c / d);   // (30) * (15/5)</span><br><span class="line">         Console.WriteLine(&quot;(a + b) * (c / d) 的值是 &#123;0&#125;&quot;, e);</span><br><span class="line">         e = a + (b * c) / d;    //  20 + (150/5)</span><br><span class="line">         Console.WriteLine(&quot;a + (b * c) / d 的值是 &#123;0&#125;&quot;, e);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(a + b) * c / d 的值是 90</span><br><span class="line">((a + b) * c) / d 的值是 90</span><br><span class="line">(a + b) * (c / d) 的值是 90</span><br><span class="line">a + (b * c) / d 的值是 50</span><br></pre></td></tr></table></figure>
<h2 id="十-C-判断"><a href="#十-C-判断" class="headerlink" title="十.C# 判断"></a>十.C# 判断</h2><p>判断结构要求程序员指定一个或多个要评估或测试的条件，以及条件为真时要执行的语句（必需的）和条件为假时要执行的语句（可选的）。</p>
<p>下面是大多数编程语言中典型的判断结构的一般形式：</p>
<p><img src=".\image\if.png" alt></p>
<h3 id="1-判断语句"><a href="#1-判断语句" class="headerlink" title="1.判断语句"></a><strong>1.判断语句</strong></h3><p>C# 提供了以下类型的判断语句。点击链接查看每个语句的细节。</p>
<table>
<thead>
<tr>
<th>语句</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-if.html" target="_blank" rel="noopener">if 语句</a></td>
<td>一个 <strong>if 语句</strong> 由一个布尔表达式后跟一个或多个语句组成。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-if-else.html" target="_blank" rel="noopener">if…else 语句</a></td>
<td>一个 <strong>if 语句</strong> 后可跟一个可选的 <strong>else 语句</strong>，else 语句在布尔表达式为假时执行。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-nested-if.html" target="_blank" rel="noopener">嵌套 if 语句</a></td>
<td>您可以在一个 <strong>if</strong> 或 <strong>else if</strong> 语句内使用另一个 <strong>if</strong> 或 <strong>else if</strong> 语句。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-switch.html" target="_blank" rel="noopener">switch 语句</a></td>
<td>一个 <strong>switch</strong> 语句允许测试一个变量等于多个值时的情况。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-nested-switch.html" target="_blank" rel="noopener">嵌套 switch 语句</a></td>
<td>您可以在一个 <strong>switch</strong> 语句内使用另一个 <strong>switch</strong> 语句。</td>
</tr>
</tbody>
</table>
<h3 id="2-运算符"><a href="#2-运算符" class="headerlink" title="2. ? : 运算符"></a><strong>2. ? : 运算符</strong></h3><p>我们已经在前面的章节中讲解了 <strong>条件运算符 ? :</strong>，可以用来替代 <strong>if…else</strong> 语句。它的一般形式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Exp1 ? Exp2 : Exp3;</span><br></pre></td></tr></table></figure>
<p>其中，Exp1、Exp2 和 Exp3 是表达式。请注意，冒号的使用和位置。</p>
<p>? 表达式的值是由 Exp1 决定的。如果 Exp1 为真，则计算 Exp2 的值，结果即为整个 ? 表达式的值。如果 Exp1 为假，则计算 Exp3 的值，结果即为整个 ? 表达式的值。</p>
<h2 id="十一-C-循环"><a href="#十一-C-循环" class="headerlink" title="十一.C# 循环"></a>十一.C# 循环</h2><p>有的时候，可能需要多次执行同一块代码。一般情况下，语句是顺序执行的：函数中的第一个语句先执行，接着是第二个语句，依此类推。</p>
<p>编程语言提供了允许更为复杂的执行路径的多种控制结构。</p>
<p>循环语句允许我们多次执行一个语句或语句组，下面是大多数编程语言中循环语句的一般形式：</p>
<p><img src=".\image\loop_architecture.jpg" alt></p>
<h3 id="1-循环类型"><a href="#1-循环类型" class="headerlink" title="1.循环类型"></a><strong>1.循环类型</strong></h3><p>C# 提供了以下几种循环类型。点击链接查看每个类型的细节。</p>
<table>
<thead>
<tr>
<th>循环类型</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-while-loop.html" target="_blank" rel="noopener">while 循环</a></td>
<td>当给定条件为真时，重复语句或语句组。它会在执行循环主体之前测试条件。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-for-loop.html" target="_blank" rel="noopener">for/foreach 循环</a></td>
<td>多次执行一个语句序列，简化管理循环变量的代码。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-do-while-loop.html" target="_blank" rel="noopener">do…while 循环</a></td>
<td>除了它是在循环主体结尾测试条件外，其他与 while 语句类似。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-nested-loops.html" target="_blank" rel="noopener">嵌套循环</a></td>
<td>您可以在 while、for 或 do..while 循环内使用一个或多个循环。</td>
</tr>
</tbody>
</table>
<h3 id="2-循环控制语句"><a href="#2-循环控制语句" class="headerlink" title="2.循环控制语句"></a><strong>2.循环控制语句</strong></h3><p>循环控制语句更改执行的正常序列。当执行离开一个范围时，所有在该范围中创建的自动对象都会被销毁。</p>
<p>C# 提供了下列的控制语句。点击链接查看每个语句的细节。</p>
<table>
<thead>
<tr>
<th>控制语句</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-break-statement.html" target="_blank" rel="noopener">break 语句</a></td>
<td>终止 <strong>loop</strong> 或 <strong>switch</strong> 语句，程序流将继续执行紧接着 loop 或 switch 的下一条语句。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-continue-statement.html" target="_blank" rel="noopener">continue 语句</a></td>
<td>引起循环跳过主体的剩余部分，立即重新开始测试条件。</td>
</tr>
</tbody>
</table>
<h3 id="3-无限循环"><a href="#3-无限循环" class="headerlink" title="3.无限循环"></a><strong>3.无限循环</strong></h3><p>如果条件永远不为假，则循环将变成无限循环。<strong>for</strong> 循环在传统意义上可用于实现无限循环。由于构成循环的三个表达式中任何一个都不是必需的，您可以将某些条件表达式留空来构成一个无限循环。</p>
<p>实例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace Loops</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            for (; ; )</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Hey! I am Trapped&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当条件表达式不存在时，它被假设为真。您也可以设置一个初始值和增量表达式，但是一般情况下，程序员偏向于使用 for(;;) 结构来表示一个无限循环。</p>
<h2 id="十二-C-封装"><a href="#十二-C-封装" class="headerlink" title="十二.C# 封装"></a>十二.C# 封装</h2><p><strong>封装</strong> 被定义为”把一个或多个项目封闭在一个物理的或者逻辑的包中”。在面向对象程序设计方法论中，封装是为了防止对实现细节的访问。</p>
<p>抽象和封装是面向对象程序设计的相关特性。抽象允许相关信息可视化，封装则使开发者<em>实现所需级别的抽象</em>。</p>
<p>C# 封装根据具体的需要，设置使用者的访问权限，并通过 <strong>访问修饰符</strong> 来实现。</p>
<p>一个 <strong>访问修饰符</strong> 定义了一个类成员的范围和可见性。C# 支持的访问修饰符如下所示：</p>
<ul>
<li>public：所有对象都可以访问；</li>
<li>private：对象本身在对象内部可以访问；</li>
<li>protected：只有该类对象及其子类对象可以访问</li>
<li>internal：同一个程序集的对象可以访问；</li>
<li>protected internal：访问限于当前程序集或派生自包含类的类型。</li>
</ul>
<h3 id="1-Public-访问修饰符"><a href="#1-Public-访问修饰符" class="headerlink" title="1. Public 访问修饰符"></a><strong>1. Public 访问修饰符</strong></h3><p>Public 访问修饰符允许一个类将其成员变量和成员函数暴露给其他的函数和对象。任何公有成员可以被外部的类访问。</p>
<p>下面的实例说明了这点：</p>
<blockquote>
<h2 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace RectangleApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Rectangle</span><br><span class="line">    &#123;</span><br><span class="line">        //成员变量</span><br><span class="line">        public double length;</span><br><span class="line">        public double width;</span><br><span class="line">        public double GetArea()</span><br><span class="line">        &#123;</span><br><span class="line">            return length * width;</span><br><span class="line">        &#125;</span><br><span class="line">        public void Display()</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;长度： &#123;0&#125;&quot;, length);</span><br><span class="line">            Console.WriteLine(&quot;宽度： &#123;0&#125;&quot;, width);</span><br><span class="line">            Console.WriteLine(&quot;面积： &#123;0&#125;&quot;, GetArea());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;// Rectangle 结束</span><br><span class="line">    class ExecuteRectangle</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Rectangle r = new Rectangle();</span><br><span class="line">            r.length = 4.5;</span><br><span class="line">            r.width = 3.5;</span><br><span class="line">            r.Display();</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">长度： 4.5</span><br><span class="line">宽度： 3.5</span><br><span class="line">面积： 15.75</span><br></pre></td></tr></table></figure>
<p>在上面的实例中，成员变量 length 和 width 被声明为 <strong>public</strong>，所以它们可以被函数 Main() 使用 Rectangle 类的实例 <strong>r</strong> 访问。</p>
<p>成员函数 <em>Display()</em> 和 <em>GetArea()</em> 可以直接访问这些变量。</p>
<p>成员函数 <em>Display()</em> 也被声明为 <strong>public</strong>，所以它也能被 <em>Main()</em> 使用 Rectangle 类的实例 <strong>r</strong> 访问。</p>
<h3 id="2-Private-访问修饰符"><a href="#2-Private-访问修饰符" class="headerlink" title="2. Private 访问修饰符"></a><strong>2. Private 访问修饰符</strong></h3><p>Private 访问修饰符允许一个类将其成员变量和成员函数对其他的函数和对象进行隐藏。只有同一个类中的函数可以访问它的私有成员。即使是类的实例也不能访问它的私有成员。</p>
<p>下面的实例说明了这点：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace RectangleApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Rectangle</span><br><span class="line">    &#123;</span><br><span class="line">        //成员变量</span><br><span class="line">        private double length;</span><br><span class="line">        private double width;</span><br><span class="line">        public void Acceptdetails()</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;请输入长度：&quot;);</span><br><span class="line">            length = Convert.ToDouble(Console.ReadLine());</span><br><span class="line">            Console.WriteLine(&quot;请输入宽度：&quot;);</span><br><span class="line">            width = Convert.ToDouble(Console.ReadLine());</span><br><span class="line">        &#125;</span><br><span class="line">        public double GetArea()</span><br><span class="line">        &#123;</span><br><span class="line">            return length * width;</span><br><span class="line">        &#125;</span><br><span class="line">        public void Display()</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;长度： &#123;0&#125;&quot;, length);</span><br><span class="line">            Console.WriteLine(&quot;宽度： &#123;0&#125;&quot;, width);</span><br><span class="line">            Console.WriteLine(&quot;面积： &#123;0&#125;&quot;, GetArea());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;//end class Rectangle    </span><br><span class="line">    class ExecuteRectangle</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Rectangle r = new Rectangle();</span><br><span class="line">            r.Acceptdetails();</span><br><span class="line">            r.Display();</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">请输入长度：</span><br><span class="line">4.4</span><br><span class="line">请输入宽度：</span><br><span class="line">3.3</span><br><span class="line">长度： 4.4</span><br><span class="line">宽度： 3.3</span><br><span class="line">面积： 14.52</span><br></pre></td></tr></table></figure>
<p>在上面的实例中，成员变量 length 和 width 被声明为 <strong>private</strong>，所以它们不能被函数 Main() 访问。</p>
<p>成员函数 <em>AcceptDetails()</em> 和 <em>Display()</em> 可以访问这些变量。</p>
<p>由于成员函数 <em>AcceptDetails()</em> 和 <em>Display()</em> 被声明为 <strong>public</strong>，所以它们可以被 <em>Main()</em> 使用 Rectangle 类的实例 <strong>r</strong> 访问。</p>
<h3 id="3-Protected-访问修饰符"><a href="#3-Protected-访问修饰符" class="headerlink" title="3. Protected 访问修饰符"></a><strong>3. Protected 访问修饰符</strong></h3><p>Protected 访问修饰符允许子类访问它的基类的成员变量和成员函数。这样有助于实现继承。我们将在继承的章节详细讨论这个。更详细地讨论这个。</p>
<h3 id="4-Internal-访问修饰符"><a href="#4-Internal-访问修饰符" class="headerlink" title="4. Internal 访问修饰符"></a><strong>4. Internal 访问修饰符</strong></h3><p>Internal 访问说明符允许一个类将其成员变量和成员函数暴露给当前程序中的其他函数和对象。换句话说，带有 internal 访问修饰符的任何成员可以被定义在该成员所定义的应用程序内的任何类或方法访问。</p>
<p>下面的实例说明了这点：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace RectangleApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Rectangle</span><br><span class="line">    &#123;</span><br><span class="line">        //成员变量</span><br><span class="line">        internal double length;</span><br><span class="line">        internal double width;</span><br><span class="line">        double GetArea()</span><br><span class="line">        &#123;</span><br><span class="line">            return length * width;</span><br><span class="line">        &#125;</span><br><span class="line">       public void Display()</span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;长度： &#123;0&#125;&quot;, length);</span><br><span class="line">            Console.WriteLine(&quot;宽度： &#123;0&#125;&quot;, width);</span><br><span class="line">            Console.WriteLine(&quot;面积： &#123;0&#125;&quot;, GetArea());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;//end class Rectangle    </span><br><span class="line">    class ExecuteRectangle</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Rectangle r = new Rectangle();</span><br><span class="line">            r.length = 4.5;</span><br><span class="line">            r.width = 3.5;</span><br><span class="line">            r.Display();</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">长度： 4.5</span><br><span class="line">宽度： 3.5</span><br><span class="line">面积： 15.75</span><br></pre></td></tr></table></figure>
<p>在上面的实例中，请注意成员函数 <em>GetArea()</em> 声明的时候不带有任何访问修饰符。如果没有指定访问修饰符，则使用类成员的默认访问修饰符，即为 <strong>private</strong>。</p>
<h3 id="5-Protected-Internal-访问修饰符"><a href="#5-Protected-Internal-访问修饰符" class="headerlink" title="5. Protected Internal 访问修饰符"></a><strong>5. Protected Internal 访问修饰符</strong></h3><p>Protected Internal 访问修饰符允许在本类,派生类或者包含该类的程序集中访问。这也被用于实现继承。</p>
<h2 id="十三-C-方法"><a href="#十三-C-方法" class="headerlink" title="十三. C# 方法"></a>十三. C# 方法</h2><p>一个方法是把一些相关的语句组织在一起，用来执行一个任务的语句块。每一个 C# 程序至少有一个带有 Main 方法的类。</p>
<p>要使用一个方法，您需要：</p>
<ul>
<li>定义方法</li>
<li>调用方法</li>
</ul>
<h3 id="1-C-中定义方法"><a href="#1-C-中定义方法" class="headerlink" title="1. C# 中定义方法"></a><strong>1. C# 中定义方法</strong></h3><p>当定义一个方法时，从根本上说是在声明它的结构的元素。在 C# 中，定义方法的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;Access Specifier&gt; &lt;Return Type&gt; &lt;Method Name&gt;(Parameter List)</span><br><span class="line">&#123;</span><br><span class="line">   Method Body</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面是方法的各个元素：</p>
<ul>
<li><strong>Access Specifier</strong>：访问修饰符，这个决定了变量或方法对于另一个类的可见性。</li>
<li><strong>Return type</strong>：返回类型，一个方法可以返回一个值。返回类型是方法返回的值的数据类型。如果方法不返回任何值，则返回类型为 <strong>void</strong>。</li>
<li><strong>Method name</strong>：方法名称，是一个唯一的标识符，且是大小写敏感的。它不能与类中声明的其他标识符相同。</li>
<li><strong>Parameter list</strong>：参数列表，使用圆括号括起来，该参数是用来传递和接收方法的数据。参数列表是指方法的参数类型、顺序和数量。参数是可选的，也就是说，一个方法可能不包含参数。</li>
<li><strong>Method body</strong>：方法主体，包含了完成任务所需的指令集。</li>
</ul>
<p>下面的代码片段显示一个函数 <em>FindMax</em>，它接受两个整数值，并返回两个中的较大值。它有 public 访问修饰符，所以它可以使用类的实例从类的外部进行访问。</p>
<blockquote>
<h2 id="实例-1"><a href="#实例-1" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">class NumberManipulator</span><br><span class="line">&#123;</span><br><span class="line">   public int FindMax(int num1, int num2)</span><br><span class="line">   &#123;</span><br><span class="line">      /* 局部变量声明 */</span><br><span class="line">      int result;</span><br><span class="line">      if (num1 &gt; num2)</span><br><span class="line">         result = num1;</span><br><span class="line">      else</span><br><span class="line">         result = num2;</span><br><span class="line">      return result;</span><br><span class="line">   &#125;</span><br><span class="line">   ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-C-中调用方法"><a href="#2-C-中调用方法" class="headerlink" title="2. C# 中调用方法"></a><strong>2. C# 中调用方法</strong></h3><p>您可以使用方法名调用方法。下面的实例演示了这点：</p>
<blockquote>
<h2 id="实例-2"><a href="#实例-2" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">   class NumberManipulator</span><br><span class="line">   &#123;</span><br><span class="line">      public int FindMax(int num1, int num2)</span><br><span class="line">      &#123;</span><br><span class="line">         /* 局部变量声明 */</span><br><span class="line">         int result;</span><br><span class="line">         if (num1 &gt; num2)</span><br><span class="line">            result = num1;</span><br><span class="line">         else</span><br><span class="line">            result = num2;</span><br><span class="line">         return result;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         /* 局部变量定义 */</span><br><span class="line">         int a = 100;</span><br><span class="line">         int b = 200;</span><br><span class="line">         int ret;</span><br><span class="line">         NumberManipulator n = new NumberManipulator();</span><br><span class="line">         //调用 FindMax 方法</span><br><span class="line">         ret = n.FindMax(a, b);</span><br><span class="line">         Console.WriteLine(&quot;最大值是： &#123;0&#125;&quot;, ret );</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">最大值是： 200</span><br></pre></td></tr></table></figure>
<p>您也可以使用类的实例从另一个类中调用其他类的公有方法。例如，方法 <em>FindMax</em> 属于 <em>NumberManipulator</em> 类，您可以从另一个类 <em>Test</em> 中调用它。</p>
<blockquote>
<h2 id="实例-3"><a href="#实例-3" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">    class NumberManipulator</span><br><span class="line">    &#123;</span><br><span class="line">        public int FindMax(int num1, int num2)</span><br><span class="line">        &#123;</span><br><span class="line">            /* 局部变量声明 */</span><br><span class="line">            int result;</span><br><span class="line">            if (num1 &gt; num2)</span><br><span class="line">                result = num1;</span><br><span class="line">            else</span><br><span class="line">                result = num2;</span><br><span class="line">            return result;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    class Test</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            /* 局部变量定义 */</span><br><span class="line">            int a = 100;</span><br><span class="line">            int b = 200;</span><br><span class="line">            int ret;</span><br><span class="line">            NumberManipulator n = new NumberManipulator();</span><br><span class="line">            //调用 FindMax 方法</span><br><span class="line">            ret = n.FindMax(a, b);</span><br><span class="line">            Console.WriteLine(&quot;最大值是： &#123;0&#125;&quot;, ret );</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">最大值是： 200</span><br></pre></td></tr></table></figure>
<h3 id="3-递归方法调用"><a href="#3-递归方法调用" class="headerlink" title="3.递归方法调用"></a><strong>3.递归方法调用</strong></h3><p>一个方法可以自我调用。这就是所谓的 <strong>递归</strong>。下面的实例使用递归函数计算一个数的阶乘：</p>
<blockquote>
<h2 id="实例-4"><a href="#实例-4" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">    class NumberManipulator</span><br><span class="line">    &#123;</span><br><span class="line">        public int factorial(int num)</span><br><span class="line">        &#123;</span><br><span class="line">            /* 局部变量定义 */</span><br><span class="line">            int result;</span><br><span class="line">            if (num == 1)</span><br><span class="line">            &#123;</span><br><span class="line">                return 1;</span><br><span class="line">            &#125;</span><br><span class="line">            else</span><br><span class="line">            &#123;</span><br><span class="line">                result = factorial(num - 1) * num;</span><br><span class="line">                return result;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            NumberManipulator n = new NumberManipulator();</span><br><span class="line">            //调用 factorial 方法</span><br><span class="line">            Console.WriteLine(&quot;6 的阶乘是： &#123;0&#125;&quot;, n.factorial(6));</span><br><span class="line">            Console.WriteLine(&quot;7 的阶乘是： &#123;0&#125;&quot;, n.factorial(7));</span><br><span class="line">            Console.WriteLine(&quot;8 的阶乘是： &#123;0&#125;&quot;, n.factorial(8));</span><br><span class="line">            Console.ReadLine();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">6 的阶乘是： 720</span><br><span class="line">7 的阶乘是： 5040</span><br><span class="line">8 的阶乘是： 40320</span><br></pre></td></tr></table></figure>
<h3 id="4-参数传递"><a href="#4-参数传递" class="headerlink" title="4.参数传递"></a><strong>4.参数传递</strong></h3><p>当调用带有参数的方法时，您需要向方法传递参数。在 C# 中，有三种向方法传递参数的方式：</p>
<table>
<thead>
<tr>
<th>方式</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>值参数</td>
<td>这种方式复制参数的实际值给函数的形式参数，实参和形参使用的是两个不同内存中的值。在这种情况下，当形参的值发生改变时，不会影响实参的值，从而保证了实参数据的安全。</td>
</tr>
<tr>
<td>引用参数</td>
<td>这种方式复制参数的内存位置的引用给形式参数。这意味着，当形参的值发生改变时，同时也改变实参的值。</td>
</tr>
<tr>
<td>输出参数</td>
<td>这种方式可以返回多个值。</td>
</tr>
</tbody>
</table>
<h3 id="5-按值传递参数"><a href="#5-按值传递参数" class="headerlink" title="5.按值传递参数"></a><strong>5.按值传递参数</strong></h3><p>这是参数传递的默认方式。在这种方式下，当调用一个方法时，会为每个值参数创建一个新的存储位置。</p>
<p>实际参数的值会复制给形参，实参和形参使用的是两个不同内存中的值。所以，当形参的值发生改变时，不会影响实参的值，从而保证了实参数据的安全。下面的实例演示了这个概念：</p>
<blockquote>
<h2 id="实例-5"><a href="#实例-5" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">   class NumberManipulator</span><br><span class="line">   &#123;</span><br><span class="line">      public void swap(int x, int y)</span><br><span class="line">      &#123;</span><br><span class="line">         int temp;</span><br><span class="line">         temp = x; /* 保存 x 的值 */</span><br><span class="line">         x = y;    /* 把 y 赋值给 x */</span><br><span class="line">         y = temp; /* 把 temp 赋值给 y */</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         NumberManipulator n = new NumberManipulator();</span><br><span class="line">         /* 局部变量定义 */</span><br><span class="line">         int a = 100;</span><br><span class="line">         int b = 200;</span><br><span class="line">         Console.WriteLine(&quot;在交换之前，a 的值： &#123;0&#125;&quot;, a);</span><br><span class="line">         Console.WriteLine(&quot;在交换之前，b 的值： &#123;0&#125;&quot;, b);</span><br><span class="line">         /* 调用函数来交换值 */</span><br><span class="line">         n.swap(a, b);</span><br><span class="line">         Console.WriteLine(&quot;在交换之后，a 的值： &#123;0&#125;&quot;, a);</span><br><span class="line">         Console.WriteLine(&quot;在交换之后，b 的值： &#123;0&#125;&quot;, b);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">在交换之前，a 的值：100</span><br><span class="line">在交换之前，b 的值：200</span><br><span class="line">在交换之后，a 的值：100</span><br><span class="line">在交换之后，b 的值：200</span><br></pre></td></tr></table></figure>
<p>结果表明，即使在函数内改变了值，值也没有发生任何的变化。</p>
<h3 id="6-按引用传递参数"><a href="#6-按引用传递参数" class="headerlink" title="6.按引用传递参数"></a><strong>6.按引用传递参数</strong></h3><p>引用参数是一个对变量的<strong>内存位置的引用</strong>。当按引用传递参数时，与值参数不同的是，它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。</p>
<p>在 C# 中，使用 <strong>ref</strong> 关键字声明引用参数。下面的实例演示了这点：</p>
<blockquote>
<h2 id="实例-6"><a href="#实例-6" class="headerlink" title="实例"></a>实例</h2></blockquote>
<p>using System;<br>namespace CalculatorApplication<br>{<br>   class NumberManipulator<br>   {<br>      public void swap(ref int x, ref int y)<br>      {<br>         int temp;<br>         temp = x; /<em> 保存 x 的值 </em>/<br>         x = y;    /<em> 把 y 赋值给 x </em>/<br>         y = temp; /<em> 把 temp 赋值给 y </em>/<br>       }<br>      static void Main(string[] args)<br>      {<br>         NumberManipulator n = new NumberManipulator();<br>         /<em> 局部变量定义 </em>/<br>         int a = 100;<br>         int b = 200;<br>         Console.WriteLine(“在交换之前，a 的值： {0}”, a);<br>         Console.WriteLine(“在交换之前，b 的值： {0}”, b);<br>         /<em> 调用函数来交换值 </em>/<br>         n.swap(ref a, ref b);<br>         Console.WriteLine(“在交换之后，a 的值： {0}”, a);<br>         Console.WriteLine(“在交换之后，b 的值： {0}”, b);<br>         Console.ReadLine();<br>      }<br>   }<br>}</p>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">在交换之前，a 的值：100</span><br><span class="line">在交换之前，b 的值：200</span><br><span class="line">在交换之后，a 的值：200</span><br><span class="line">在交换之后，b 的值：100</span><br></pre></td></tr></table></figure>
<p>结果表明，<em>swap</em> 函数内的值改变了，且这个改变可以在 <em>Main</em> 函数中反映出来。</p>
<h3 id="7-按输出传递参数"><a href="#7-按输出传递参数" class="headerlink" title="7.按输出传递参数"></a><strong>7.按输出传递参数</strong></h3><p>return 语句可用于只从函数中返回一个值。但是，可以使用 <strong>输出参数</strong> 来从函数中返回两个值。输出参数会把方法输出的数据赋给自己，其他方面与引用参数相似。</p>
<p>下面的实例演示了这点：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">   class NumberManipulator</span><br><span class="line">   &#123;</span><br><span class="line">      public void getValue(out int x )</span><br><span class="line">      &#123;</span><br><span class="line">         int temp = 5;</span><br><span class="line">         x = temp;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         NumberManipulator n = new NumberManipulator();</span><br><span class="line">         /* 局部变量定义 */</span><br><span class="line">         int a = 100;</span><br><span class="line">         Console.WriteLine(&quot;在方法调用之前，a 的值： &#123;0&#125;&quot;, a);</span><br><span class="line">         /* 调用函数来获取值 */</span><br><span class="line">         n.getValue(out a);</span><br><span class="line">         Console.WriteLine(&quot;在方法调用之后，a 的值： &#123;0&#125;&quot;, a);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">在方法调用之前，a 的值： 100</span><br><span class="line">在方法调用之后，a 的值： 5</span><br></pre></td></tr></table></figure>
<p>提供给输出参数的变量不需要赋值。当需要从一个参数没有指定初始值的方法中返回值时，输出参数特别有用。请看下面的实例，来理解这一点：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">   class NumberManipulator</span><br><span class="line">   &#123;</span><br><span class="line">      public void getValues(out int x, out int y )</span><br><span class="line">      &#123;</span><br><span class="line">          Console.WriteLine(&quot;请输入第一个值： &quot;);</span><br><span class="line">          x = Convert.ToInt32(Console.ReadLine());</span><br><span class="line">          Console.WriteLine(&quot;请输入第二个值： &quot;);</span><br><span class="line">          y = Convert.ToInt32(Console.ReadLine());</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         NumberManipulator n = new NumberManipulator();</span><br><span class="line">         /* 局部变量定义 */</span><br><span class="line">         int a , b;</span><br><span class="line">         /* 调用函数来获取值 */</span><br><span class="line">         n.getValues(out a, out b);</span><br><span class="line">         Console.WriteLine(&quot;在方法调用之后，a 的值： &#123;0&#125;&quot;, a);</span><br><span class="line">         Console.WriteLine(&quot;在方法调用之后，b 的值： &#123;0&#125;&quot;, b);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果（取决于用户输入）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">请输入第一个值：</span><br><span class="line">7</span><br><span class="line">请输入第二个值：</span><br><span class="line">8</span><br><span class="line">在方法调用之后，a 的值： 7</span><br><span class="line">在方法调用之后，b 的值： 8</span><br></pre></td></tr></table></figure>
<h2 id="十四-C-可空类型（Nullable）"><a href="#十四-C-可空类型（Nullable）" class="headerlink" title="十四.C# 可空类型（Nullable）"></a>十四.C# 可空类型（Nullable）</h2><h3 id="1-C-单问号-与-双问号"><a href="#1-C-单问号-与-双问号" class="headerlink" title="1. C# 单问号 ? 与 双问号 ??"></a>1. C# 单问号 ? 与 双问号 ??</h3><p>? : 单问号用于对 int,double,bool 等无法直接赋值为 null 的数据类型进行 null 的赋值，意思是这个数据类型是 NullAble 类型的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">int? i = 3 </span><br><span class="line">等同于</span><br><span class="line">Nullable&lt;int&gt; i = new Nullable&lt;int&gt;(3);</span><br><span class="line"></span><br><span class="line">int i; //默认值0</span><br><span class="line">int? ii; //默认值null</span><br></pre></td></tr></table></figure>
<p>?? : 双问号 可用于判断一个变量在为 null 时返回一个指定的值。</p>
<p>接下来我们详细说明。</p>
<h3 id="2-C-可空类型（Nullable）"><a href="#2-C-可空类型（Nullable）" class="headerlink" title="2. C# 可空类型（Nullable）"></a>2. C# 可空类型（Nullable）</h3><p>C# 提供了一个特殊的数据类型，<strong>nullable</strong> 类型（可空类型），可空类型可以表示其基础值类型正常范围内的值，再加上一个 null 值。</p>
<p>例如，Nullable&lt; Int32 &gt;，读作”可空的 Int32”，可以被赋值为 -2,147,483,648 到 2,147,483,647 之间的任意值，也可以被赋值为 null 值。类似的，Nullable&lt; bool &gt; 变量可以被赋值为 true 或 false 或 null。</p>
<p>在处理数据库和其他包含可能未赋值的元素的数据类型时，将 null 赋值给数值类型或布尔型的功能特别有用。例如，数据库中的布尔型字段可以存储值 true 或 false，或者，该字段也可以未定义。</p>
<p>声明一个 <strong>nullable</strong> 类型（可空类型）的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt; data_type&gt; ? &lt;variable_name&gt; = null;</span><br></pre></td></tr></table></figure>
<p>下面的实例演示了可空数据类型的用法：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">   class NullablesAtShow</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         int? num1 = null;</span><br><span class="line">         int? num2 = 45;</span><br><span class="line">         double? num3 = new double?();</span><br><span class="line">         double? num4 = 3.14157;</span><br><span class="line">         bool? boolval = new bool?();</span><br><span class="line">         // 显示值</span><br><span class="line">         Console.WriteLine(&quot;显示可空类型的值： &#123;0&#125;, &#123;1&#125;, &#123;2&#125;, &#123;3&#125;&quot;, </span><br><span class="line">                            num1, num2, num3, num4);</span><br><span class="line">         Console.WriteLine(&quot;一个可空的布尔值： &#123;0&#125;&quot;, boolval);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">显示可空类型的值： , 45,  , 3.14157</span><br><span class="line">一个可空的布尔值：</span><br></pre></td></tr></table></figure>
<h3 id="3-Null-合并运算符（-）"><a href="#3-Null-合并运算符（-）" class="headerlink" title="3. Null 合并运算符（ ?? ）"></a>3. Null 合并运算符（ ?? ）</h3><p>Null 合并运算符用于定义可空类型和引用类型的默认值。Null 合并运算符为类型转换定义了一个预设值，以防可空类型的值为 Null。Null 合并运算符把操作数类型隐式转换为另一个可空（或不可空）的值类型的操作数的类型。</p>
<p>如果第一个操作数的值为 null，则运算符返回第二个操作数的值，否则返回第一个操作数的值。下面的实例演示了这点：</p>
<blockquote>
<h2 id="实例-7"><a href="#实例-7" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace CalculatorApplication</span><br><span class="line">&#123;</span><br><span class="line">   class NullablesAtShow</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         double? num1 = null;</span><br><span class="line">         double? num2 = 3.14157;</span><br><span class="line">         double num3;</span><br><span class="line">         num3 = num1 ?? 5.34;      // num1 如果为空值则返回 5.34</span><br><span class="line">         Console.WriteLine(&quot;num3 的值： &#123;0&#125;&quot;, num3);</span><br><span class="line">         num3 = num2 ?? 5.34;</span><br><span class="line">         Console.WriteLine(&quot;num3 的值： &#123;0&#125;&quot;, num3);</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">num3 的值： 5.34</span><br><span class="line">num3 的值： 3.14157</span><br></pre></td></tr></table></figure>
<h2 id="十五-C-数组（Array）"><a href="#十五-C-数组（Array）" class="headerlink" title="十五.C# 数组（Array）"></a>十五.C# 数组（Array）</h2><p>数组是一个存储相同类型元素的固定大小的顺序集合。数组是用来存储数据的集合，通常认为数组是一个同一类型变量的集合。</p>
<p>声明数组变量并不是声明 number0、number1、…、number99 一个个单独的变量，而是声明一个就像 numbers 这样的变量，然后使用 numbers[0]、numbers[1]、…、numbers[99] 来表示一个个单独的变量。数组中某个指定的元素是通过索引来访问的。</p>
<p>所有的数组都是由连续的内存位置组成的。最低的地址对应第一个元素，最高的地址对应最后一个元素。</p>
<p><img src=".\image\arrays.jpg" alt></p>
<h3 id="1-声明数组"><a href="#1-声明数组" class="headerlink" title="1. 声明数组"></a>1. 声明数组</h3><p>在 C# 中声明一个数组，您可以使用下面的语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">datatype[] arrayName;</span><br></pre></td></tr></table></figure>
<p>其中，</p>
<ul>
<li><em>datatype</em> 用于指定被存储在数组中的元素的类型。</li>
<li><em>[ ]</em> 指定数组的秩（维度）。秩指定数组的大小。</li>
<li><em>arrayName</em> 指定数组的名称。</li>
</ul>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">double[] balance;</span><br></pre></td></tr></table></figure>
<h3 id="2-初始化数组"><a href="#2-初始化数组" class="headerlink" title="2. 初始化数组"></a>2. 初始化数组</h3><p>声明一个数组不会在内存中初始化数组。当初始化数组变量时，您可以赋值给数组。</p>
<p>数组是一个引用类型，所以您需要使用 <strong>new</strong> 关键字来创建数组的实例。</p>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">double[] balance = new double[10];</span><br></pre></td></tr></table></figure>
<h3 id="3-赋值给数组"><a href="#3-赋值给数组" class="headerlink" title="3. 赋值给数组"></a>3. 赋值给数组</h3><p>您可以通过使用索引号赋值给一个单独的数组元素，比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">double[] balance = new double[10];</span><br><span class="line">balance[0] = 4500.0;</span><br></pre></td></tr></table></figure>
<p>您可以在声明数组的同时给数组赋值，比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">double[] balance = &#123; 2340.0, 4523.69, 3421.0&#125;;</span><br></pre></td></tr></table></figure>
<p>您也可以创建并初始化一个数组，比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int [] marks = new int[5]  &#123; 99,  98, 92, 97, 95&#125;;</span><br></pre></td></tr></table></figure>
<p>在上述情况下，你也可以省略数组的大小，比如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int [] marks = new int[]  &#123; 99,  98, 92, 97, 95&#125;;</span><br></pre></td></tr></table></figure>
<p>您也可以赋值一个数组变量到另一个目标数组变量中。在这种情况下，目标和源会指向相同的内存位置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int [] marks = new int[]  &#123; 99,  98, 92, 97, 95&#125;;</span><br><span class="line">int[] score = marks;</span><br></pre></td></tr></table></figure>
<p>当您创建一个数组时，C# 编译器会根据数组类型隐式初始化每个数组元素为一个默认值。例如，int 数组的所有元素都会被初始化为 0。</p>
<h3 id="4-访问数组元素"><a href="#4-访问数组元素" class="headerlink" title="4. 访问数组元素"></a>4. 访问数组元素</h3><p>元素是通过带索引的数组名称来访问的。这是通过把元素的索引放置在数组名称后的方括号中来实现的。例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">double salary = balance[9];</span><br></pre></td></tr></table></figure>
<p>下面是一个实例，使用上面提到的三个概念，即声明、赋值、访问数组：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace ArrayApplication</span><br><span class="line">&#123;</span><br><span class="line">   class MyArray</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         int []  n = new int[10]; /* n 是一个带有 10 个整数的数组 */</span><br><span class="line">         int i,j;</span><br><span class="line">         /* 初始化数组 n 中的元素 */         </span><br><span class="line">         for ( i = 0; i &lt; 10; i++ )</span><br><span class="line">         &#123;</span><br><span class="line">            n[ i ] = i + 100;</span><br><span class="line">         &#125;</span><br><span class="line">         /* 输出每个数组元素的值 */</span><br><span class="line">         for (j = 0; j &lt; 10; j++ )</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(&quot;Element[&#123;0&#125;] = &#123;1&#125;&quot;, j, n[j]);</span><br><span class="line">         &#125;</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Element[0] = 100</span><br><span class="line">Element[1] = 101</span><br><span class="line">Element[2] = 102</span><br><span class="line">Element[3] = 103</span><br><span class="line">Element[4] = 104</span><br><span class="line">Element[5] = 105</span><br><span class="line">Element[6] = 106</span><br><span class="line">Element[7] = 107</span><br><span class="line">Element[8] = 108</span><br><span class="line">Element[9] = 109</span><br></pre></td></tr></table></figure>
<h3 id="5-使用-foreach-循环"><a href="#5-使用-foreach-循环" class="headerlink" title="5. 使用 foreach 循环"></a>5. 使用 <em>foreach</em> 循环</h3><p>在前面的实例中，我们使用一个 for 循环来访问每个数组元素。您也可以使用一个 <strong>foreach</strong> 语句来遍历数组。</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace ArrayApplication</span><br><span class="line">&#123;</span><br><span class="line">   class MyArray</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         int []  n = new int[10]; /* n 是一个带有 10 个整数的数组 */</span><br><span class="line">         /* 初始化数组 n 中的元素 */         </span><br><span class="line">         for ( int i = 0; i &lt; 10; i++ )</span><br><span class="line">         &#123;</span><br><span class="line">            n[i] = i + 100;</span><br><span class="line">         &#125;</span><br><span class="line">         /* 输出每个数组元素的值 */</span><br><span class="line">         foreach (int j in n )</span><br><span class="line">         &#123;</span><br><span class="line">            int i = j-100;</span><br><span class="line">            Console.WriteLine(&quot;Element[&#123;0&#125;] = &#123;1&#125;&quot;, i, j);</span><br><span class="line">         &#125;</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Element[0] = 100</span><br><span class="line">Element[1] = 101</span><br><span class="line">Element[2] = 102</span><br><span class="line">Element[3] = 103</span><br><span class="line">Element[4] = 104</span><br><span class="line">Element[5] = 105</span><br><span class="line">Element[6] = 106</span><br><span class="line">Element[7] = 107</span><br><span class="line">Element[8] = 108</span><br><span class="line">Element[9] = 109</span><br></pre></td></tr></table></figure>
<h3 id="6-C-数组细节"><a href="#6-C-数组细节" class="headerlink" title="6. C# 数组细节"></a>6. C# 数组细节</h3><p>在 C# 中，数组是非常重要的，且需要了解更多的细节。下面列出了 C# 程序员必须清楚的一些与数组相关的重要概念：</p>
<table>
<thead>
<tr>
<th>概念</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-multi-dimensional-arrays.html" target="_blank" rel="noopener">多维数组</a></td>
<td>C# 支持多维数组。多维数组最简单的形式是二维数组。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-jagged-arrays.html" target="_blank" rel="noopener">交错数组</a></td>
<td>C# 支持交错数组，即数组的数组。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-passing-arrays-to-functions.html" target="_blank" rel="noopener">传递数组给函数</a></td>
<td>您可以通过指定不带索引的数组名称来给函数传递一个指向数组的指针。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-param-arrays.html" target="_blank" rel="noopener">参数数组</a></td>
<td>这通常用于传递未知数量的参数给函数。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-array-class.html" target="_blank" rel="noopener">Array 类</a></td>
<td>在 System 命名空间中定义，是所有数组的基类，并提供了各种用于数组的属性和方法。</td>
</tr>
</tbody>
</table>
<h2 id="十六-C-字符串（String）"><a href="#十六-C-字符串（String）" class="headerlink" title="十六. C# 字符串（String）"></a>十六. C# 字符串（String）</h2><p>在 C# 中，您可以使用字符数组来表示字符串，但是，更常见的做法是使用 <strong>string</strong> 关键字来声明一个字符串变量。string 关键字是 <strong>System.String</strong> 类的别名。</p>
<h3 id="1-创建-String-对象"><a href="#1-创建-String-对象" class="headerlink" title="1. 创建 String 对象"></a>1. 创建 String 对象</h3><p>您可以使用以下方法之一来创建 string 对象：</p>
<ul>
<li>通过给 String 变量指定一个字符串</li>
<li>通过使用 String 类构造函数</li>
<li>通过使用字符串串联运算符（ + ）</li>
<li>通过检索属性或调用一个返回字符串的方法</li>
<li>通过格式化方法来转换一个值或对象为它的字符串表示形式</li>
</ul>
<p>下面的实例演示了这点：</p>
<blockquote>
<h2 id="实例-8"><a href="#实例-8" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace StringApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">           //字符串，字符串连接</span><br><span class="line">            string fname, lname;</span><br><span class="line">            fname = &quot;Rowan&quot;;</span><br><span class="line">            lname = &quot;Atkinson&quot;;</span><br><span class="line">            string fullname = fname + lname;</span><br><span class="line">            Console.WriteLine(&quot;Full Name: &#123;0&#125;&quot;, fullname);</span><br><span class="line">            //通过使用 string 构造函数</span><br><span class="line">            char[] letters = &#123; &apos;H&apos;, &apos;e&apos;, &apos;l&apos;, &apos;l&apos;,&apos;o&apos; &#125;;</span><br><span class="line">            string greetings = new string(letters);</span><br><span class="line">            Console.WriteLine(&quot;Greetings: &#123;0&#125;&quot;, greetings);</span><br><span class="line">            //方法返回字符串</span><br><span class="line">            string[] sarray = &#123; &quot;Hello&quot;, &quot;From&quot;, &quot;Tutorials&quot;, &quot;Point&quot; &#125;;</span><br><span class="line">            string message = String.Join(&quot; &quot;, sarray);</span><br><span class="line">            Console.WriteLine(&quot;Message: &#123;0&#125;&quot;, message);</span><br><span class="line">            //用于转化值的格式化方法</span><br><span class="line">            DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);</span><br><span class="line">            string chat = String.Format(&quot;Message sent at &#123;0:t&#125; on &#123;0:D&#125;&quot;, </span><br><span class="line">            waiting);</span><br><span class="line">            Console.WriteLine(&quot;Message: &#123;0&#125;&quot;, chat);</span><br><span class="line">            Console.ReadKey() ;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Full Name: RowanAtkinson</span><br><span class="line">Greetings: Hello</span><br><span class="line">Message: Hello From Tutorials Point</span><br><span class="line">Message: Message sent at 17:58 on Wednesday, 10 October 2012</span><br></pre></td></tr></table></figure>
<h3 id="2-String-类的属性"><a href="#2-String-类的属性" class="headerlink" title="2. String 类的属性"></a>2. String 类的属性</h3><p>String 类有以下两个属性：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>属性名称 &amp; 描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><strong>Chars</strong>在当前 <em>String</em> 对象中获取 <em>Char</em> 对象的指定位置。</td>
</tr>
<tr>
<td>2</td>
<td><strong>Length</strong>在当前的 <em>String</em> 对象中获取字符数。</td>
</tr>
</tbody>
</table>
<h3 id="3-String-类的方法"><a href="#3-String-类的方法" class="headerlink" title="3. String 类的方法"></a>3. String 类的方法</h3><p>String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>方法名称 &amp; 描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><strong>public static int Compare( string strA, string strB )</strong> 比较两个指定的 string 对象，并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。</td>
</tr>
<tr>
<td>2</td>
<td><strong>public static int Compare( string strA, string strB, bool ignoreCase )</strong> 比较两个指定的 string 对象，并返回一个表示它们在排列顺序中相对位置的整数。但是，如果布尔参数为真时，该方法不区分大小写。</td>
</tr>
<tr>
<td>3</td>
<td><strong>public static string Concat( string str0, string str1 )</strong> 连接两个 string 对象。</td>
</tr>
<tr>
<td>4</td>
<td><strong>public static string Concat( string str0, string str1, string str2 )</strong> 连接三个 string 对象。</td>
</tr>
<tr>
<td>5</td>
<td><strong>public static string Concat( string str0, string str1, string str2, string str3 )</strong> 连接四个 string 对象。</td>
</tr>
<tr>
<td>6</td>
<td><strong>public bool Contains( string value )</strong> 返回一个表示指定 string 对象是否出现在字符串中的值。</td>
</tr>
<tr>
<td>7</td>
<td><strong>public static string Copy( string str )</strong> 创建一个与指定字符串具有相同值的新的 String 对象。</td>
</tr>
<tr>
<td>8</td>
<td><strong>public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )</strong> 从 string 对象的指定位置开始复制指定数量的字符到 Unicode 字符数组中的指定位置。</td>
</tr>
<tr>
<td>9</td>
<td><strong>public bool EndsWith( string value )</strong> 判断 string 对象的结尾是否匹配指定的字符串。</td>
</tr>
<tr>
<td>10</td>
<td><strong>public bool Equals( string value )</strong> 判断当前的 string 对象是否与指定的 string 对象具有相同的值。</td>
</tr>
<tr>
<td>11</td>
<td><strong>public static bool Equals( string a, string b )</strong> 判断两个指定的 string 对象是否具有相同的值。</td>
</tr>
<tr>
<td>12</td>
<td><strong>public static string Format( string format, Object arg0 )</strong> 把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。</td>
</tr>
<tr>
<td>13</td>
<td><strong>public int IndexOf( char value )</strong> 返回指定 Unicode 字符在当前字符串中第一次出现的索引，索引从 0 开始。</td>
</tr>
<tr>
<td>14</td>
<td><strong>public int IndexOf( string value )</strong> 返回指定字符串在该实例中第一次出现的索引，索引从 0 开始。</td>
</tr>
<tr>
<td>15</td>
<td><strong>public int IndexOf( char value, int startIndex )</strong> 返回指定 Unicode 字符从该字符串中指定字符位置开始搜索第一次出现的索引，索引从 0 开始。</td>
</tr>
<tr>
<td>16</td>
<td><strong>public int IndexOf( string value, int startIndex )</strong> 返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引，索引从 0 开始。</td>
</tr>
<tr>
<td>17</td>
<td><strong>public int IndexOfAny( char[] anyOf )</strong> 返回某一个指定的 Unicode 字符数组中任意字符在该实例中第一次出现的索引，索引从 0 开始。</td>
</tr>
<tr>
<td>18</td>
<td><strong>public int IndexOfAny( char[] anyOf, int startIndex )</strong> 返回某一个指定的 Unicode 字符数组中任意字符从该实例中指定字符位置开始搜索第一次出现的索引，索引从 0 开始。</td>
</tr>
<tr>
<td>19</td>
<td><strong>public string Insert( int startIndex, string value )</strong> 返回一个新的字符串，其中，指定的字符串被插入在当前 string 对象的指定索引位置。</td>
</tr>
<tr>
<td>20</td>
<td><strong>public static bool IsNullOrEmpty( string value )</strong> 指示指定的字符串是否为 null 或者是否为一个空的字符串。</td>
</tr>
<tr>
<td>21</td>
<td><strong>public static string Join( string separator, string[] value )</strong> 连接一个字符串数组中的所有元素，使用指定的分隔符分隔每个元素。</td>
</tr>
<tr>
<td>22</td>
<td><strong>public static string Join( string separator, string[] value, int startIndex, int count )</strong> 连接接一个字符串数组中的指定位置开始的指定元素，使用指定的分隔符分隔每个元素。</td>
</tr>
<tr>
<td>23</td>
<td><strong>public int LastIndexOf( char value )</strong> 返回指定 Unicode 字符在当前 string 对象中最后一次出现的索引位置，索引从 0 开始。</td>
</tr>
<tr>
<td>24</td>
<td><strong>public int LastIndexOf( string value )</strong> 返回指定字符串在当前 string 对象中最后一次出现的索引位置，索引从 0 开始。</td>
</tr>
<tr>
<td>25</td>
<td><strong>public string Remove( int startIndex )</strong> 移除当前实例中的所有字符，从指定位置开始，一直到最后一个位置为止，并返回字符串。</td>
</tr>
<tr>
<td>26</td>
<td><strong>public string Remove( int startIndex, int count )</strong> 从当前字符串的指定位置开始移除指定数量的字符，并返回字符串。</td>
</tr>
<tr>
<td>27</td>
<td><strong>public string Replace( char oldChar, char newChar )</strong> 把当前 string 对象中，所有指定的 Unicode 字符替换为另一个指定的 Unicode 字符，并返回新的字符串。</td>
</tr>
<tr>
<td>28</td>
<td><strong>public string Replace( string oldValue, string newValue )</strong> 把当前 string 对象中，所有指定的字符串替换为另一个指定的字符串，并返回新的字符串。</td>
</tr>
<tr>
<td>29</td>
<td><strong>public string[] Split( params char[] separator )</strong> 返回一个字符串数组，包含当前的 string 对象中的子字符串，子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。</td>
</tr>
<tr>
<td>30</td>
<td><strong>public string[] Split( char[] separator, int count )</strong> 返回一个字符串数组，包含当前的 string 对象中的子字符串，子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。int 参数指定要返回的子字符串的最大数目。</td>
</tr>
<tr>
<td>31</td>
<td><strong>public bool StartsWith( string value )</strong> 判断字符串实例的开头是否匹配指定的字符串。</td>
</tr>
<tr>
<td>32</td>
<td><strong>public char[] ToCharArray()</strong>返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。</td>
</tr>
<tr>
<td>33</td>
<td><strong>public char[] ToCharArray( int startIndex, int length )</strong> 返回一个带有当前 string 对象中所有字符的 Unicode 字符数组，从指定的索引开始，直到指定的长度为止。</td>
</tr>
<tr>
<td>34</td>
<td><strong>public string ToLower()</strong>把字符串转换为小写并返回。</td>
</tr>
<tr>
<td>35</td>
<td><strong>public string ToUpper()</strong>把字符串转换为大写并返回。</td>
</tr>
<tr>
<td>36</td>
<td><strong>public string Trim()</strong>移除当前 String 对象中的所有前导空白字符和后置空白字符。</td>
</tr>
</tbody>
</table>
<p>上面的方法列表并不详尽，请访问 MSDN 库，查看完整的方法列表和 String 类构造函数。</p>
<p>下面的实例演示了上面提到的一些方法：</p>
<p><strong>比较字符串</strong></p>
<blockquote>
<h2 id="实例-9"><a href="#实例-9" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace StringApplication</span><br><span class="line">&#123;</span><br><span class="line">   class StringProg</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         string str1 = &quot;This is test&quot;;</span><br><span class="line">         string str2 = &quot;This is text&quot;;</span><br><span class="line">         if (String.Compare(str1, str2) == 0)</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(str1 + &quot; and &quot; + str2 +  &quot; are equal.&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         else</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(str1 + &quot; and &quot; + str2 + &quot; are not equal.&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         Console.ReadKey() ;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">This is test and This is text are not equal.</span><br></pre></td></tr></table></figure>
<p><strong>字符串包含字符串：</strong></p>
<blockquote>
<h2 id="实例-10"><a href="#实例-10" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace StringApplication</span><br><span class="line">&#123;</span><br><span class="line">   class StringProg</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         string str = &quot;This is test&quot;;</span><br><span class="line">         if (str.Contains(&quot;test&quot;))</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(&quot;The sequence &apos;test&apos; was found.&quot;);</span><br><span class="line">         &#125;</span><br><span class="line">         Console.ReadKey() ;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">The sequence &apos;test&apos; was found.</span><br></pre></td></tr></table></figure>
<p><strong>获取子字符串：</strong></p>
<blockquote>
<h2 id="实例-11"><a href="#实例-11" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">using System; </span><br><span class="line">namespace StringApplication </span><br><span class="line">&#123;</span><br><span class="line">        class StringProg </span><br><span class="line">        &#123; </span><br><span class="line">                static void Main(string[] args) </span><br><span class="line">                &#123; </span><br><span class="line">                        string str = &quot;Last night I dreamt of San Pedro&quot;; </span><br><span class="line">                        Console.WriteLine(str); </span><br><span class="line">                        string substr = str.Substring(23); </span><br><span class="line">                        Console.WriteLine(substr); </span><br><span class="line">                        Console.ReadKey() ; </span><br><span class="line">                &#125; </span><br><span class="line">        &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行实例 »</p>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Last night I dreamt of San Pedro</span><br><span class="line">San Pedro</span><br></pre></td></tr></table></figure>
<p><strong>连接字符串：</strong></p>
<blockquote>
<h2 id="实例-12"><a href="#实例-12" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace StringApplication</span><br><span class="line">&#123;</span><br><span class="line">   class StringProg</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         string[] starray = new string[]&#123;&quot;Down the way nights are dark&quot;,</span><br><span class="line">         &quot;And the sun shines daily on the mountain top&quot;,</span><br><span class="line">         &quot;I took a trip on a sailing ship&quot;,</span><br><span class="line">         &quot;And when I reached Jamaica&quot;,</span><br><span class="line">         &quot;I made a stop&quot;&#125;;</span><br><span class="line">         string str = String.Join(&quot;\n&quot;, starray);</span><br><span class="line">         Console.WriteLine(str);</span><br><span class="line">         Console.ReadKey() ;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Down the way nights are dark</span><br><span class="line">And the sun shines daily on the mountain top</span><br><span class="line">I took a trip on a sailing ship</span><br><span class="line">And when I reached Jamaica</span><br><span class="line">I made a stop</span><br></pre></td></tr></table></figure>
<h2 id="十七-C-结构体（Struct）"><a href="#十七-C-结构体（Struct）" class="headerlink" title="十七. C# 结构体（Struct）"></a>十七. C# 结构体（Struct）</h2><p>在 C# 中，结构体是值类型数据结构。它使得一个单一变量可以存储各种数据类型的相关数据。<strong>struct</strong> 关键字用于创建结构体。</p>
<p>结构体是用来代表一个记录。假设您想跟踪图书馆中书的动态。您可能想跟踪每本书的以下属性：</p>
<ul>
<li>Title</li>
<li>Author</li>
<li>Subject</li>
<li>Book ID</li>
</ul>
<h3 id="1-定义结构体"><a href="#1-定义结构体" class="headerlink" title="1. 定义结构体"></a>1. 定义结构体</h3><p>为了定义一个结构体，您必须使用 struct 语句。struct 语句为程序定义了一个带有多个成员的新的数据类型。</p>
<p>例如，您可以按照如下的方式声明 Book 结构：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">struct Books</span><br><span class="line">&#123;</span><br><span class="line">   public string title;</span><br><span class="line">   public string author;</span><br><span class="line">   public string subject;</span><br><span class="line">   public int book_id;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>下面的程序演示了结构的用法：</p>
<blockquote>
<h2 id="实例-13"><a href="#实例-13" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.Text;</span><br><span class="line">struct Books</span><br><span class="line">&#123;</span><br><span class="line">   public string title;</span><br><span class="line">   public string author;</span><br><span class="line">   public string subject;</span><br><span class="line">   public int book_id;</span><br><span class="line">&#125;;  </span><br><span class="line">public class testStructure</span><br><span class="line">&#123;</span><br><span class="line">   public static void Main(string[] args)</span><br><span class="line">   &#123;</span><br><span class="line">      Books Book1;        /* 声明 Book1，类型为 Book */</span><br><span class="line">      Books Book2;        /* 声明 Book2，类型为 Book */</span><br><span class="line">      /* book 1 详述 */</span><br><span class="line">      Book1.title = &quot;C Programming&quot;;</span><br><span class="line">      Book1.author = &quot;Nuha Ali&quot;; </span><br><span class="line">      Book1.subject = &quot;C Programming Tutorial&quot;;</span><br><span class="line">      Book1.book_id = 6495407;</span><br><span class="line">      /* book 2 详述 */</span><br><span class="line">      Book2.title = &quot;Telecom Billing&quot;;</span><br><span class="line">      Book2.author = &quot;Zara Ali&quot;;</span><br><span class="line">      Book2.subject =  &quot;Telecom Billing Tutorial&quot;;</span><br><span class="line">      Book2.book_id = 6495700;</span><br><span class="line">      /* 打印 Book1 信息 */</span><br><span class="line">      Console.WriteLine( &quot;Book 1 title : &#123;0&#125;&quot;, Book1.title);</span><br><span class="line">      Console.WriteLine(&quot;Book 1 author : &#123;0&#125;&quot;, Book1.author);</span><br><span class="line">      Console.WriteLine(&quot;Book 1 subject : &#123;0&#125;&quot;, Book1.subject);</span><br><span class="line">      Console.WriteLine(&quot;Book 1 book_id :&#123;0&#125;&quot;, Book1.book_id);</span><br><span class="line">      /* 打印 Book2 信息 */</span><br><span class="line">      Console.WriteLine(&quot;Book 2 title : &#123;0&#125;&quot;, Book2.title);</span><br><span class="line">      Console.WriteLine(&quot;Book 2 author : &#123;0&#125;&quot;, Book2.author);</span><br><span class="line">      Console.WriteLine(&quot;Book 2 subject : &#123;0&#125;&quot;, Book2.subject);</span><br><span class="line">      Console.WriteLine(&quot;Book 2 book_id : &#123;0&#125;&quot;, Book2.book_id);       </span><br><span class="line">      Console.ReadKey();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Book 1 title : C Programming</span><br><span class="line">Book 1 author : Nuha Ali</span><br><span class="line">Book 1 subject : C Programming Tutorial</span><br><span class="line">Book 1 book_id : 6495407</span><br><span class="line">Book 2 title : Telecom Billing</span><br><span class="line">Book 2 author : Zara Ali</span><br><span class="line">Book 2 subject : Telecom Billing Tutorial</span><br><span class="line">Book 2 book_id : 6495700</span><br></pre></td></tr></table></figure>
<h3 id="2-C-结构的特点"><a href="#2-C-结构的特点" class="headerlink" title="2. C# 结构的特点"></a>2. C# 结构的特点</h3><p>您已经用了一个简单的名为 Books 的结构。在 C# 中的结构与传统的 C 或 C++ 中的结构不同。C# 中的结构有以下特点：</p>
<ul>
<li>结构可带有方法、字段、索引、属性、运算符方法和事件。</li>
<li>结构可定义构造函数，但不能定义析构函数。但是，您不能为结构定义默认的构造函数。默认的构造函数是自动定义的，且不能被改变。</li>
<li>与类不同，结构不能继承其他的结构或类。</li>
<li>结构不能作为其他结构或类的基础结构。</li>
<li>结构可实现一个或多个接口。</li>
<li>结构成员不能指定为 abstract、virtual 或 protected。</li>
<li>当您使用 <strong>New</strong> 操作符创建一个结构对象时，会调用适当的构造函数来创建结构。与类不同，结构可以不使用 New 操作符即可被实例化。</li>
<li>如果不使用 New 操作符，只有在所有的字段都被初始化之后，字段才被赋值，对象才被使用。</li>
</ul>
<h3 id="3-类-vs-结构"><a href="#3-类-vs-结构" class="headerlink" title="3. 类 vs 结构"></a>3. 类 vs 结构</h3><p>类和结构有以下几个基本的不同点：</p>
<ul>
<li>类是引用类型，结构是值类型。</li>
<li>结构不支持继承。</li>
<li>结构不能声明默认的构造函数。</li>
</ul>
<p>针对上述讨论，让我们重写前面的实例：</p>
<blockquote>
<p>实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.Text;</span><br><span class="line">struct Books</span><br><span class="line">&#123;</span><br><span class="line">   private string title;</span><br><span class="line">   private string author;</span><br><span class="line">   private string subject;</span><br><span class="line">   private int book_id;</span><br><span class="line">   public void getValues(string t, string a, string s, int id)</span><br><span class="line">   &#123;</span><br><span class="line">      title = t;</span><br><span class="line">      author = a;</span><br><span class="line">      subject = s;</span><br><span class="line">      book_id =id; </span><br><span class="line">   &#125;</span><br><span class="line">   public void display()</span><br><span class="line">   &#123;</span><br><span class="line">      Console.WriteLine(&quot;Title : &#123;0&#125;&quot;, title);</span><br><span class="line">      Console.WriteLine(&quot;Author : &#123;0&#125;&quot;, author);</span><br><span class="line">      Console.WriteLine(&quot;Subject : &#123;0&#125;&quot;, subject);</span><br><span class="line">      Console.WriteLine(&quot;Book_id :&#123;0&#125;&quot;, book_id);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;;  </span><br><span class="line">public class testStructure</span><br><span class="line">&#123;</span><br><span class="line">   public static void Main(string[] args)</span><br><span class="line">   &#123;</span><br><span class="line">      Books Book1 = new Books(); /* 声明 Book1，类型为 Book */</span><br><span class="line">      Books Book2 = new Books(); /* 声明 Book2，类型为 Book */</span><br><span class="line">      /* book 1 详述 */</span><br><span class="line">      Book1.getValues(&quot;C Programming&quot;,</span><br><span class="line">      &quot;Nuha Ali&quot;, &quot;C Programming Tutorial&quot;,6495407);</span><br><span class="line">      /* book 2 详述 */</span><br><span class="line">      Book2.getValues(&quot;Telecom Billing&quot;,</span><br><span class="line">      &quot;Zara Ali&quot;, &quot;Telecom Billing Tutorial&quot;, 6495700);</span><br><span class="line">      /* 打印 Book1 信息 */</span><br><span class="line">      Book1.display();</span><br><span class="line">      /* 打印 Book2 信息 */</span><br><span class="line">      Book2.display(); </span><br><span class="line">      Console.ReadKey();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Title : C Programming</span><br><span class="line">Author : Nuha Ali</span><br><span class="line">Subject : C Programming Tutorial</span><br><span class="line">Book_id : 6495407</span><br><span class="line">Title : Telecom Billing</span><br><span class="line">Author : Zara Ali</span><br><span class="line">Subject : Telecom Billing Tutorial</span><br><span class="line">Book_id : 6495700</span><br></pre></td></tr></table></figure>
<h2 id="十八-C-枚举（Enum）"><a href="#十八-C-枚举（Enum）" class="headerlink" title="十八. C# 枚举（Enum）"></a>十八. C# 枚举（Enum）</h2><p>枚举是一组命名整型常量。枚举类型是使用 <strong>enum</strong> 关键字声明的。</p>
<p>C# 枚举是值类型。换句话说，枚举包含自己的值，且不能继承或传递继承。</p>
<h3 id="1-声明-enum-变量"><a href="#1-声明-enum-变量" class="headerlink" title="1. 声明 enum 变量"></a>1. 声明 <em>enum</em> 变量</h3><p>声明枚举的一般语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">enum &lt;enum_name&gt;</span><br><span class="line">&#123; </span><br><span class="line">    enumeration list </span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>其中，</p>
<ul>
<li><em>enum_name</em> 指定枚举的类型名称。</li>
<li><em>enumeration list</em> 是一个用逗号分隔的标识符列表。</li>
</ul>
<p>枚举列表中的每个符号代表一个整数值，一个比它前面的符号大的整数值。默认情况下，第一个枚举符号的值是 0.例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">enum Days &#123; Sun, Mon, tue, Wed, thu, Fri, Sat &#125;;</span><br></pre></td></tr></table></figure>
<p>下面的实例演示了枚举变量的用法：</p>
<blockquote>
<h2 id="实例-14"><a href="#实例-14" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">public class EnumTest</span><br><span class="line">&#123;</span><br><span class="line">    enum Day &#123; Sun, Mon, Tue, Wed, Thu, Fri, Sat &#125;;</span><br><span class="line">    static void Main()</span><br><span class="line">    &#123;</span><br><span class="line">        int x = (int)Day.Sun;</span><br><span class="line">        int y = (int)Day.Fri;</span><br><span class="line">        Console.WriteLine(&quot;Sun = &#123;0&#125;&quot;, x);</span><br><span class="line">        Console.WriteLine(&quot;Fri = &#123;0&#125;&quot;, y);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Sun = 0</span><br><span class="line">Fri = 5</span><br></pre></td></tr></table></figure>
<h2 id="十九-C-类（Class）"><a href="#十九-C-类（Class）" class="headerlink" title="十九. C# 类（Class）"></a>十九. C# 类（Class）</h2><p>当你定义一个类时，你定义了一个数据类型的蓝图。这实际上并没有定义任何的数据，但它定义了类的名称意味着什么，也就是说，类的对象由什么组成及在这个对象上可执行什么操作。对象是类的实例。构成类的方法和变量成为类的成员。</p>
<h3 id="1-类的定义"><a href="#1-类的定义" class="headerlink" title="1. 类的定义"></a>1. 类的定义</h3><p>类的定义是以关键字 <strong>class</strong> 开始，后跟类的名称。类的主体，包含在一对花括号内。下面是类定义的一般形式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;access specifier&gt; class  class_name </span><br><span class="line">&#123;</span><br><span class="line">    // member variables</span><br><span class="line">    &lt;access specifier&gt; &lt;data type&gt; variable1;</span><br><span class="line">    &lt;access specifier&gt; &lt;data type&gt; variable2;</span><br><span class="line">    ...</span><br><span class="line">    &lt;access specifier&gt; &lt;data type&gt; variableN;</span><br><span class="line">    // member methods</span><br><span class="line">    &lt;access specifier&gt; &lt;return type&gt; method1(parameter_list) </span><br><span class="line">    &#123;</span><br><span class="line">        // method body </span><br><span class="line">    &#125;</span><br><span class="line">    &lt;access specifier&gt; &lt;return type&gt; method2(parameter_list) </span><br><span class="line">    &#123;</span><br><span class="line">        // method body </span><br><span class="line">    &#125;</span><br><span class="line">    ...</span><br><span class="line">    &lt;access specifier&gt; &lt;return type&gt; methodN(parameter_list) </span><br><span class="line">    &#123;</span><br><span class="line">        // method body </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>请注意：</strong></p>
<ul>
<li>访问标识符 <access specifier> 指定了对类及其成员的访问规则。如果没有指定，则使用默认的访问标识符。类的默认访问标识符是 <strong>internal</strong>，成员的默认访问标识符是 <strong>private</strong>。</access></li>
<li>数据类型 <data type> 指定了变量的类型，返回类型 <return type> 指定了返回的方法返回的数据类型。</return></data></li>
<li>如果要访问类的成员，你要使用点（.）运算符。</li>
<li>点运算符链接了对象的名称和成员的名称。</li>
</ul>
<p>下面的实例说明了目前为止所讨论的概念：</p>
<blockquote>
<h2 id="实例-15"><a href="#实例-15" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace BoxApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Box</span><br><span class="line">    &#123;</span><br><span class="line">       public double length;   // 长度</span><br><span class="line">       public double breadth;  // 宽度</span><br><span class="line">       public double height;   // 高度</span><br><span class="line">    &#125;</span><br><span class="line">    class Boxtester</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Box Box1 = new Box();        // 声明 Box1，类型为 Box</span><br><span class="line">            Box Box2 = new Box();        // 声明 Box2，类型为 Box</span><br><span class="line">            double volume = 0.0;         // 体积</span><br><span class="line">            // Box1 详述</span><br><span class="line">            Box1.height = 5.0;</span><br><span class="line">            Box1.length = 6.0;</span><br><span class="line">            Box1.breadth = 7.0;</span><br><span class="line">            // Box2 详述</span><br><span class="line">            Box2.height = 10.0;</span><br><span class="line">            Box2.length = 12.0;</span><br><span class="line">            Box2.breadth = 13.0;</span><br><span class="line">            // Box1 的体积</span><br><span class="line">            volume = Box1.height * Box1.length * Box1.breadth;</span><br><span class="line">            Console.WriteLine(&quot;Box1 的体积： &#123;0&#125;&quot;,  volume);</span><br><span class="line">            // Box2 的体积</span><br><span class="line">            volume = Box2.height * Box2.length * Box2.breadth;</span><br><span class="line">            Console.WriteLine(&quot;Box2 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Box1 的体积： 210</span><br><span class="line">Box2 的体积： 1560</span><br></pre></td></tr></table></figure>
<h3 id="2-成员函数和封装"><a href="#2-成员函数和封装" class="headerlink" title="2. 成员函数和封装"></a>2. 成员函数和封装</h3><p>类的成员函数是一个在类定义中有它的定义或原型的函数，就像其他变量一样。作为类的一个成员，它能在类的任何对象上操作，且能访问该对象的类的所有成员。</p>
<p>成员变量是对象的属性（从设计角度），且它们保持私有来实现封装。这些变量只能使用公共成员函数来访问。</p>
<p>让我们使用上面的概念来设置和获取一个类中不同的类成员的值：</p>
<blockquote>
<h2 id="实例-16"><a href="#实例-16" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace BoxApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Box</span><br><span class="line">    &#123;</span><br><span class="line">       private double length;   // 长度</span><br><span class="line">       private double breadth;  // 宽度</span><br><span class="line">       private double height;   // 高度</span><br><span class="line">       public void setLength( double len )</span><br><span class="line">       &#123;</span><br><span class="line">            length = len;</span><br><span class="line">       &#125;</span><br><span class="line">       public void setBreadth( double bre )</span><br><span class="line">       &#123;</span><br><span class="line">            breadth = bre;</span><br><span class="line">       &#125;</span><br><span class="line">       public void setHeight( double hei )</span><br><span class="line">       &#123;</span><br><span class="line">            height = hei;</span><br><span class="line">       &#125;</span><br><span class="line">       public double getVolume()</span><br><span class="line">       &#123;</span><br><span class="line">           return length * breadth * height;</span><br><span class="line">       &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    class Boxtester</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            Box Box1 = new Box();        // 声明 Box1，类型为 Box</span><br><span class="line">            Box Box2 = new Box();                // 声明 Box2，类型为 Box</span><br><span class="line">            double volume;                               // 体积</span><br><span class="line">            // Box1 详述</span><br><span class="line">            Box1.setLength(6.0);</span><br><span class="line">            Box1.setBreadth(7.0);</span><br><span class="line">            Box1.setHeight(5.0);</span><br><span class="line">            // Box2 详述</span><br><span class="line">            Box2.setLength(12.0);</span><br><span class="line">            Box2.setBreadth(13.0);</span><br><span class="line">            Box2.setHeight(10.0);</span><br><span class="line">            // Box1 的体积</span><br><span class="line">            volume = Box1.getVolume();</span><br><span class="line">            Console.WriteLine(&quot;Box1 的体积： &#123;0&#125;&quot; ,volume);</span><br><span class="line">            // Box2 的体积</span><br><span class="line">            volume = Box2.getVolume();</span><br><span class="line">            Console.WriteLine(&quot;Box2 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Box1 的体积： 210</span><br><span class="line">Box2 的体积： 1560</span><br></pre></td></tr></table></figure>
<h3 id="3-C-中的构造函数"><a href="#3-C-中的构造函数" class="headerlink" title="3. C# 中的构造函数"></a>3. C# 中的构造函数</h3><p>类的 <strong>构造函数</strong> 是类的一个特殊的成员函数，当创建类的新对象时执行。</p>
<p>构造函数的名称与类的名称完全相同，它没有任何返回类型。</p>
<p>下面的实例说明了构造函数的概念：</p>
<blockquote>
<h2 id="实例-17"><a href="#实例-17" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace LineApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Line</span><br><span class="line">   &#123;</span><br><span class="line">      private double length;   // 线条的长度</span><br><span class="line">      public Line()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;对象已创建&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      public void setLength( double len )</span><br><span class="line">      &#123;</span><br><span class="line">         length = len;</span><br><span class="line">      &#125;</span><br><span class="line">      public double getLength()</span><br><span class="line">      &#123;</span><br><span class="line">         return length;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Line line = new Line();    </span><br><span class="line">         // 设置线条长度</span><br><span class="line">         line.setLength(6.0);</span><br><span class="line">         Console.WriteLine(&quot;线条的长度： &#123;0&#125;&quot;, line.getLength());</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">对象已创建</span><br><span class="line">线条的长度： 6</span><br></pre></td></tr></table></figure>
<p><strong>默认的构造函数</strong>没有任何参数。但是如果你需要一个带有参数的构造函数可以有参数，这种构造函数叫做<strong>参数化构造函数</strong>。这种技术可以帮助你在创建对象的同时给对象赋初始值，具体请看下面实例：</p>
<blockquote>
<h2 id="实例-18"><a href="#实例-18" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace LineApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Line</span><br><span class="line">   &#123;</span><br><span class="line">      private double length;   // 线条的长度</span><br><span class="line">      public Line(double len)  // 参数化构造函数</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;对象已创建，length = &#123;0&#125;&quot;, len);</span><br><span class="line">         length = len;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setLength( double len )</span><br><span class="line">      &#123;</span><br><span class="line">         length = len;</span><br><span class="line">      &#125;</span><br><span class="line">      public double getLength()</span><br><span class="line">      &#123;</span><br><span class="line">         return length;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Line line = new Line(10.0);</span><br><span class="line">         Console.WriteLine(&quot;线条的长度： &#123;0&#125;&quot;, line.getLength()); </span><br><span class="line">         // 设置线条长度</span><br><span class="line">         line.setLength(6.0);</span><br><span class="line">         Console.WriteLine(&quot;线条的长度： &#123;0&#125;&quot;, line.getLength()); </span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">对象已创建，length = 10</span><br><span class="line">线条的长度： 10</span><br><span class="line">线条的长度： 6</span><br></pre></td></tr></table></figure>
<h3 id="4-C-中的析构函数"><a href="#4-C-中的析构函数" class="headerlink" title="4. C# 中的析构函数"></a>4. C# 中的析构函数</h3><p>类的 <strong>析构函数</strong> 是类的一个特殊的成员函数，当类的对象超出范围时执行。</p>
<p>析构函数的名称是在类的名称前加上一个波浪形（~）作为前缀，它不返回值，也不带任何参数。</p>
<p>析构函数用于在结束程序（比如关闭文件、释放内存等）之前释放资源。析构函数不能继承或重载。</p>
<p>下面的实例说明了析构函数的概念：</p>
<blockquote>
<h2 id="实例-19"><a href="#实例-19" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace LineApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Line</span><br><span class="line">   &#123;</span><br><span class="line">      private double length;   // 线条的长度</span><br><span class="line">      public Line()  // 构造函数</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;对象已创建&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      ~Line() //析构函数</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;对象已删除&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">      public void setLength( double len )</span><br><span class="line">      &#123;</span><br><span class="line">         length = len;</span><br><span class="line">      &#125;</span><br><span class="line">      public double getLength()</span><br><span class="line">      &#123;</span><br><span class="line">         return length;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Line line = new Line();</span><br><span class="line">         // 设置线条长度</span><br><span class="line">         line.setLength(6.0);</span><br><span class="line">         Console.WriteLine(&quot;线条的长度： &#123;0&#125;&quot;, line.getLength());           </span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">对象已创建</span><br><span class="line">线条的长度： 6</span><br><span class="line">对象已删除</span><br></pre></td></tr></table></figure>
<h3 id="5-C-类的静态成员"><a href="#5-C-类的静态成员" class="headerlink" title="5. C# 类的静态成员"></a>5. C# 类的静态成员</h3><p>我们可以使用 <strong>static</strong> 关键字把类成员定义为静态的。当我们声明一个类成员为静态时，意味着无论有多少个类的对象被创建，只会有一个该静态成员的副本。</p>
<p>关键字 <strong>static</strong> 意味着类中只有一个该成员的实例。静态变量用于定义常量，因为它们的值可以通过直接调用类而不需要创建类的实例来获取。静态变量可在成员函数或类的定义外部进行初始化。你也可以在类的定义内部初始化静态变量。</p>
<p>下面的实例演示了<strong>静态变量</strong>的用法：</p>
<blockquote>
<h2 id="实例-20"><a href="#实例-20" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace StaticVarApplication</span><br><span class="line">&#123;</span><br><span class="line">    class StaticVar</span><br><span class="line">    &#123;</span><br><span class="line">       public static int num;</span><br><span class="line">        public void count()</span><br><span class="line">        &#123;</span><br><span class="line">            num++;</span><br><span class="line">        &#125;</span><br><span class="line">        public int getNum()</span><br><span class="line">        &#123;</span><br><span class="line">            return num;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    class StaticTester</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            StaticVar s1 = new StaticVar();</span><br><span class="line">            StaticVar s2 = new StaticVar();</span><br><span class="line">            s1.count();</span><br><span class="line">            s1.count();</span><br><span class="line">            s1.count();</span><br><span class="line">            s2.count();</span><br><span class="line">            s2.count();</span><br><span class="line">            s2.count();         </span><br><span class="line">            Console.WriteLine(&quot;s1 的变量 num： &#123;0&#125;&quot;, s1.getNum());</span><br><span class="line">            Console.WriteLine(&quot;s2 的变量 num： &#123;0&#125;&quot;, s2.getNum());</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">s1 的变量 num： 6</span><br><span class="line">s2 的变量 num： 6</span><br></pre></td></tr></table></figure>
<p>你也可以把一个<strong>成员函数</strong>声明为 <strong>static</strong>。这样的函数只能访问静态变量。静态函数在对象被创建之前就已经存在。下面的实例演示了<strong>静态函数</strong>的用法：</p>
<blockquote>
<h2 id="实例-21"><a href="#实例-21" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace StaticVarApplication</span><br><span class="line">&#123;</span><br><span class="line">    class StaticVar</span><br><span class="line">    &#123;</span><br><span class="line">       public static int num;</span><br><span class="line">        public void count()</span><br><span class="line">        &#123;</span><br><span class="line">            num++;</span><br><span class="line">        &#125;</span><br><span class="line">        public static int getNum()</span><br><span class="line">        &#123;</span><br><span class="line">            return num;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    class StaticTester</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            StaticVar s = new StaticVar();</span><br><span class="line">            s.count();</span><br><span class="line">            s.count();</span><br><span class="line">            s.count();                   </span><br><span class="line">            Console.WriteLine(&quot;变量 num： &#123;0&#125;&quot;, StaticVar.getNum());</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">变量 num： 3</span><br></pre></td></tr></table></figure>
<h2 id="二十-C-继承"><a href="#二十-C-继承" class="headerlink" title="二十. C# 继承"></a>二十. C# 继承</h2><p>继承是面向对象程序设计中最重要的概念之一。继承允许我们根据一个类来定义另一个类，这使得创建和维护应用程序变得更容易。同时也有利于重用代码和节省开发时间。</p>
<p>当创建一个类时，程序员不需要完全重新编写新的数据成员和成员函数，只需要设计一个新的类，继承了已有的类的成员即可。这个已有的类被称为的<strong>基类</strong>，这个新的类被称为<strong>派生类</strong>。</p>
<p>继承的思想实现了 <strong>属于（IS-A）</strong> 关系。例如，哺乳动物 <strong>属于（IS-A）</strong> 动物，狗 <strong>属于（IS-A）</strong> 哺乳动物，因此狗 <strong>属于（IS-A）</strong> 动物。</p>
<h3 id="1-基类和派生类"><a href="#1-基类和派生类" class="headerlink" title="1. 基类和派生类"></a>1. 基类和派生类</h3><p>一个类可以派生自多个类或接口，这意味着它可以从多个基类或接口继承数据和函数。</p>
<p>C# 中创建派生类的语法如下：</p>
<p>&lt;访问修饰符符&gt; class &lt;基类&gt;<br>{<br> …<br>}<br>class &lt;派生类&gt; : &lt;基类&gt;<br>{<br> …<br>}</p>
<p>假设，有一个基类 Shape，它的派生类是 Rectangle：</p>
<blockquote>
<h2 id="实例-22"><a href="#实例-22" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace InheritanceApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Shape </span><br><span class="line">   &#123;</span><br><span class="line">      public void setWidth(int w)</span><br><span class="line">      &#123;</span><br><span class="line">         width = w;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setHeight(int h)</span><br><span class="line">      &#123;</span><br><span class="line">         height = h;</span><br><span class="line">      &#125;</span><br><span class="line">      protected int width;</span><br><span class="line">      protected int height;</span><br><span class="line">   &#125;</span><br><span class="line">   // 派生类</span><br><span class="line">   class Rectangle: Shape</span><br><span class="line">   &#123;</span><br><span class="line">      public int getArea()</span><br><span class="line">      &#123; </span><br><span class="line">         return (width * height); </span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class RectangleTester</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Rectangle Rect = new Rectangle();</span><br><span class="line">         Rect.setWidth(5);</span><br><span class="line">         Rect.setHeight(7);</span><br><span class="line">         // 打印对象的面积</span><br><span class="line">         Console.WriteLine(&quot;总面积： &#123;0&#125;&quot;,  Rect.getArea());</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">总面积： 35</span><br></pre></td></tr></table></figure>
<h3 id="2-基类的初始化"><a href="#2-基类的初始化" class="headerlink" title="2. 基类的初始化"></a>2. 基类的初始化</h3><p>派生类继承了基类的成员变量和成员方法。因此父类对象应在子类对象创建之前被创建。您可以在成员初始化列表中进行父类的初始化。</p>
<p>下面的程序演示了这点：</p>
<blockquote>
<h2 id="实例-23"><a href="#实例-23" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace RectangleApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Rectangle</span><br><span class="line">   &#123;</span><br><span class="line">      // 成员变量</span><br><span class="line">      protected double length;</span><br><span class="line">      protected double width;</span><br><span class="line">      public Rectangle(double l, double w)</span><br><span class="line">      &#123;</span><br><span class="line">         length = l;</span><br><span class="line">         width = w;</span><br><span class="line">      &#125;</span><br><span class="line">      public double GetArea()</span><br><span class="line">      &#123;</span><br><span class="line">         return length * width;</span><br><span class="line">      &#125;</span><br><span class="line">      public void Display()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;长度： &#123;0&#125;&quot;, length);</span><br><span class="line">         Console.WriteLine(&quot;宽度： &#123;0&#125;&quot;, width);</span><br><span class="line">         Console.WriteLine(&quot;面积： &#123;0&#125;&quot;, GetArea());</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;//end class Rectangle  </span><br><span class="line">   class Tabletop : Rectangle</span><br><span class="line">   &#123;</span><br><span class="line">      private double cost;</span><br><span class="line">      public Tabletop(double l, double w) : base(l, w)</span><br><span class="line">      &#123; &#125;</span><br><span class="line">      public double GetCost()</span><br><span class="line">      &#123;</span><br><span class="line">         double cost;</span><br><span class="line">         cost = GetArea() * 70;</span><br><span class="line">         return cost;</span><br><span class="line">      &#125;</span><br><span class="line">      public void Display()</span><br><span class="line">      &#123;</span><br><span class="line">         base.Display();</span><br><span class="line">         Console.WriteLine(&quot;成本： &#123;0&#125;&quot;, GetCost());</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class ExecuteRectangle</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Tabletop t = new Tabletop(4.5, 7.5);</span><br><span class="line">         t.Display();</span><br><span class="line">         Console.ReadLine();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">长度： 4.5</span><br><span class="line">宽度： 7.5</span><br><span class="line">面积： 33.75</span><br><span class="line">成本： 2362.5</span><br></pre></td></tr></table></figure>
<h3 id="3-C-多重继承"><a href="#3-C-多重继承" class="headerlink" title="3. C# 多重继承"></a>3. C# 多重继承</h3><p>多重继承指的是一个类别可以同时从多于一个父类继承行为与特征的功能。与单一继承相对，单一继承指一个类别只可以继承自一个父类。</p>
<p><strong>C# 不支持多重继承</strong>。但是，您可以使用接口来实现多重继承。下面的程序演示了这点：</p>
<blockquote>
<h2 id="实例-24"><a href="#实例-24" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace InheritanceApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Shape </span><br><span class="line">   &#123;</span><br><span class="line">      public void setWidth(int w)</span><br><span class="line">      &#123;</span><br><span class="line">         width = w;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setHeight(int h)</span><br><span class="line">      &#123;</span><br><span class="line">         height = h;</span><br><span class="line">      &#125;</span><br><span class="line">      protected int width;</span><br><span class="line">      protected int height;</span><br><span class="line">   &#125;</span><br><span class="line">   // 基类 PaintCost</span><br><span class="line">   public interface PaintCost </span><br><span class="line">   &#123;</span><br><span class="line">      int getCost(int area);</span><br><span class="line">   &#125;</span><br><span class="line">   // 派生类</span><br><span class="line">   class Rectangle : Shape, PaintCost</span><br><span class="line">   &#123;</span><br><span class="line">      public int getArea()</span><br><span class="line">      &#123;</span><br><span class="line">         return (width * height);</span><br><span class="line">      &#125;</span><br><span class="line">      public int getCost(int area)</span><br><span class="line">      &#123;</span><br><span class="line">         return area * 70;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class RectangleTester</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Rectangle Rect = new Rectangle();</span><br><span class="line">         int area;</span><br><span class="line">         Rect.setWidth(5);</span><br><span class="line">         Rect.setHeight(7);</span><br><span class="line">         area = Rect.getArea();</span><br><span class="line">         // 打印对象的面积</span><br><span class="line">         Console.WriteLine(&quot;总面积： &#123;0&#125;&quot;,  Rect.getArea());</span><br><span class="line">         Console.WriteLine(&quot;油漆总成本： $&#123;0&#125;&quot; , Rect.getCost(area));</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">总面积： 35</span><br><span class="line">油漆总成本： $2450</span><br></pre></td></tr></table></figure>
<h2 id="二十一-C-多态性"><a href="#二十一-C-多态性" class="headerlink" title="二十一. C# 多态性"></a>二十一. C# 多态性</h2><p><strong>多态性</strong>意味着有多重形式。在面向对象编程范式中，多态性往往表现为”一个接口，多个功能”。</p>
<p>多态性可以是静态的或动态的。在<strong>静态多态性</strong>中，函数的响应是在编译时发生的。在<strong>动态多态性</strong>中，函数的响应是在运行时发生的。</p>
<h3 id="1-静态多态性"><a href="#1-静态多态性" class="headerlink" title="1. 静态多态性"></a>1. 静态多态性</h3><p>在编译时，函数和对象的连接机制被称为早期绑定，也被称为静态绑定。C# 提供了两种技术来实现静态多态性。分别为：</p>
<ul>
<li>函数重载</li>
<li>运算符重载</li>
</ul>
<p>运算符重载将在下一章节讨论，接下来我们将讨论函数重载。</p>
<hr>
<h3 id="2-函数重载"><a href="#2-函数重载" class="headerlink" title="2. 函数重载"></a>2. 函数重载</h3><p>您可以在同一个范围内对相同的函数名有多个定义。函数的定义必须彼此不同，可以是参数列表中的参数类型不同，也可以是参数个数不同。不能重载只有返回类型不同的函数声明。</p>
<p>下面的实例演示了几个相同的函数 <strong>print()</strong>，用于打印不同的数据类型：</p>
<blockquote>
<h2 id="实例-25"><a href="#实例-25" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace PolymorphismApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Printdata</span><br><span class="line">   &#123;</span><br><span class="line">      void print(int i)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Printing int: &#123;0&#125;&quot;, i );</span><br><span class="line">      &#125;</span><br><span class="line">      void print(double f)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Printing float: &#123;0&#125;&quot; , f);</span><br><span class="line">      &#125;</span><br><span class="line">      void print(string s)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Printing string: &#123;0&#125;&quot;, s);</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Printdata p = new Printdata();</span><br><span class="line">         // 调用 print 来打印整数</span><br><span class="line">         p.print(5);</span><br><span class="line">         // 调用 print 来打印浮点数</span><br><span class="line">         p.print(500.263);</span><br><span class="line">         // 调用 print 来打印字符串</span><br><span class="line">         p.print(&quot;Hello C++&quot;);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Printing int: 5</span><br><span class="line">Printing float: 500.263</span><br><span class="line">Printing string: Hello C++</span><br></pre></td></tr></table></figure>
<hr>
<h3 id="3-动态多态性"><a href="#3-动态多态性" class="headerlink" title="3. 动态多态性"></a>3. 动态多态性</h3><p>C# 允许您使用关键字 <strong>abstract</strong> 创建抽象类，用于提供接口的部分类的实现。当一个派生类继承自该抽象类时，实现即完成。<strong>抽象类</strong>包含抽象方法，抽象方法可被派生类实现。派生类具有更专业的功能。</p>
<p>请注意，下面是有关抽象类的一些规则：</p>
<ul>
<li>您不能创建一个抽象类的实例。</li>
<li>您不能在一个抽象类外部声明一个抽象方法。</li>
<li>通过在类定义前面放置关键字 <strong>sealed</strong>，可以将类声明为<strong>密封类</strong>。当一个类被声明为 <strong>sealed</strong> 时，它不能被继承。抽象类不能被声明为 sealed。</li>
</ul>
<p>下面的程序演示了一个抽象类：</p>
<blockquote>
<h2 id="实例-26"><a href="#实例-26" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace PolymorphismApplication</span><br><span class="line">&#123;</span><br><span class="line">   abstract class Shape</span><br><span class="line">   &#123;</span><br><span class="line">       abstract public int area();</span><br><span class="line">   &#125;</span><br><span class="line">   class Rectangle:  Shape</span><br><span class="line">   &#123;</span><br><span class="line">      private int length;</span><br><span class="line">      private int width;</span><br><span class="line">      public Rectangle( int a=0, int b=0)</span><br><span class="line">      &#123;</span><br><span class="line">         length = a;</span><br><span class="line">         width = b;</span><br><span class="line">      &#125;</span><br><span class="line">      public override int area ()</span><br><span class="line">      &#123; </span><br><span class="line">         Console.WriteLine(&quot;Rectangle 类的面积：&quot;);</span><br><span class="line">         return (width * length); </span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class RectangleTester</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Rectangle r = new Rectangle(10, 7);</span><br><span class="line">         double a = r.area();</span><br><span class="line">         Console.WriteLine(&quot;面积： &#123;0&#125;&quot;,a);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Rectangle 类的面积：</span><br><span class="line">面积： 70</span><br></pre></td></tr></table></figure>
<p>当有一个定义在类中的函数需要在继承类中实现时，可以使用<strong>虚方法</strong>。虚方法是使用关键字 <strong>virtual</strong> 声明的。虚方法可以在不同的继承类中有不同的实现。对虚方法的调用是在运行时发生的。</p>
<p>动态多态性是通过 <strong>抽象类</strong> 和 <strong>虚方法</strong> 实现的。</p>
<p>下面的程序演示了这点：</p>
<blockquote>
<h2 id="实例-27"><a href="#实例-27" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace PolymorphismApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Shape </span><br><span class="line">   &#123;</span><br><span class="line">      protected int width, height;</span><br><span class="line">      public Shape( int a=0, int b=0)</span><br><span class="line">      &#123;</span><br><span class="line">         width = a;</span><br><span class="line">         height = b;</span><br><span class="line">      &#125;</span><br><span class="line">      public virtual int area()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;父类的面积：&quot;);</span><br><span class="line">         return 0;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class Rectangle: Shape</span><br><span class="line">   &#123;</span><br><span class="line">      public Rectangle( int a=0, int b=0): base(a, b)</span><br><span class="line">      &#123;</span><br><span class="line">      &#125;</span><br><span class="line">      public override int area ()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Rectangle 类的面积：&quot;);</span><br><span class="line">         return (width * height); </span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class Triangle: Shape</span><br><span class="line">   &#123;</span><br><span class="line">      public Triangle(int a = 0, int b = 0): base(a, b)</span><br><span class="line">      &#123;</span><br><span class="line">      &#125;</span><br><span class="line">      public override int area()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Triangle 类的面积：&quot;);</span><br><span class="line">         return (width * height / 2); </span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class Caller</span><br><span class="line">   &#123;</span><br><span class="line">      public void CallArea(Shape sh)</span><br><span class="line">      &#123;</span><br><span class="line">         int a;</span><br><span class="line">         a = sh.area();</span><br><span class="line">         Console.WriteLine(&quot;面积： &#123;0&#125;&quot;, a);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;  </span><br><span class="line">   class Tester</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Caller c = new Caller();</span><br><span class="line">         Rectangle r = new Rectangle(10, 7);</span><br><span class="line">         Triangle t = new Triangle(10, 5);</span><br><span class="line">         c.CallArea(r);</span><br><span class="line">         c.CallArea(t);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Rectangle 类的面积：</span><br><span class="line">面积：70</span><br><span class="line">Triangle 类的面积：</span><br><span class="line">面积：25</span><br></pre></td></tr></table></figure>
<h2 id="二十二-C-运算符重载"><a href="#二十二-C-运算符重载" class="headerlink" title="二十二.C# 运算符重载"></a>二十二.C# 运算符重载</h2><p>您可以重定义或重载 C# 中内置的运算符。因此，程序员也可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数，是通过关键字 <strong>operator</strong> 后跟运算符的符号来定义的。与其他函数一样，重载运算符有返回类型和参数列表。</p>
<p>例如，请看下面的函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public static Box operator+ (Box b, Box c)</span><br><span class="line">&#123;</span><br><span class="line">   Box box = new Box();</span><br><span class="line">   box.length = b.length + c.length;</span><br><span class="line">   box.breadth = b.breadth + c.breadth;</span><br><span class="line">   box.height = b.height + c.height;</span><br><span class="line">   return box;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的函数为用户自定义的类 Box 实现了加法运算符（+）。它把两个 Box 对象的属性相加，并返回相加后的 Box 对象。</p>
<h3 id="1-运算符重载的实现"><a href="#1-运算符重载的实现" class="headerlink" title="1. 运算符重载的实现"></a>1. 运算符重载的实现</h3><p>下面的程序演示了完整的实现：</p>
<blockquote>
<h2 id="实例-28"><a href="#实例-28" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorOvlApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Box</span><br><span class="line">   &#123;</span><br><span class="line">      private double length;      // 长度</span><br><span class="line">      private double breadth;     // 宽度</span><br><span class="line">      private double height;      // 高度</span><br><span class="line">      public double getVolume()</span><br><span class="line">      &#123;</span><br><span class="line">         return length * breadth * height;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setLength( double len )</span><br><span class="line">      &#123;</span><br><span class="line">         length = len;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setBreadth( double bre )</span><br><span class="line">      &#123;</span><br><span class="line">         breadth = bre;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setHeight( double hei )</span><br><span class="line">      &#123;</span><br><span class="line">         height = hei;</span><br><span class="line">      &#125;</span><br><span class="line">      // 重载 + 运算符来把两个 Box 对象相加</span><br><span class="line">      public static Box operator+ (Box b, Box c)</span><br><span class="line">      &#123;</span><br><span class="line">         Box box = new Box();</span><br><span class="line">         box.length = b.length + c.length;</span><br><span class="line">         box.breadth = b.breadth + c.breadth;</span><br><span class="line">         box.height = b.height + c.height;</span><br><span class="line">         return box;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class Tester</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Box Box1 = new Box();         // 声明 Box1，类型为 Box</span><br><span class="line">         Box Box2 = new Box();         // 声明 Box2，类型为 Box</span><br><span class="line">         Box Box3 = new Box();         // 声明 Box3，类型为 Box</span><br><span class="line">         double volume = 0.0;          // 体积</span><br><span class="line">         // Box1 详述</span><br><span class="line">         Box1.setLength(6.0);</span><br><span class="line">         Box1.setBreadth(7.0);</span><br><span class="line">         Box1.setHeight(5.0);</span><br><span class="line">         // Box2 详述</span><br><span class="line">         Box2.setLength(12.0);</span><br><span class="line">         Box2.setBreadth(13.0);</span><br><span class="line">         Box2.setHeight(10.0);</span><br><span class="line">         // Box1 的体积</span><br><span class="line">         volume = Box1.getVolume();</span><br><span class="line">         Console.WriteLine(&quot;Box1 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">         // Box2 的体积</span><br><span class="line">         volume = Box2.getVolume();</span><br><span class="line">         Console.WriteLine(&quot;Box2 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">         // 把两个对象相加</span><br><span class="line">         Box3 = Box1 + Box2;</span><br><span class="line">         // Box3 的体积</span><br><span class="line">         volume = Box3.getVolume();</span><br><span class="line">         Console.WriteLine(&quot;Box3 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Box1 的体积： 210</span><br><span class="line">Box2 的体积： 1560</span><br><span class="line">Box3 的体积： 5400</span><br></pre></td></tr></table></figure>
<h3 id="2-可重载和不可重载运算符"><a href="#2-可重载和不可重载运算符" class="headerlink" title="2. 可重载和不可重载运算符"></a>2. 可重载和不可重载运算符</h3><p>下表描述了 C# 中运算符重载的能力：</p>
<table>
<thead>
<tr>
<th>运算符</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>+, -, !, ~, ++, –</td>
<td>这些一元运算符只有一个操作数，且可以被重载。</td>
</tr>
<tr>
<td>+, -, *, /, %</td>
<td>这些二元运算符带有两个操作数，且可以被重载。</td>
</tr>
<tr>
<td>==, !=, &lt;, &gt;, &lt;=, &gt;=</td>
<td>这些比较运算符可以被重载。</td>
</tr>
<tr>
<td>&amp;&amp;, \</td>
<td>\</td>
<td></td>
<td>这些条件逻辑运算符不能被直接重载。</td>
</tr>
<tr>
<td>+=, -=, *=, /=, %=</td>
<td>这些赋值运算符不能被重载。</td>
</tr>
<tr>
<td>=, ., ?:, -&gt;, new, is, sizeof, typeof</td>
<td>这些运算符不能被重载。</td>
</tr>
</tbody>
</table>
<p>针对上述讨论，让我们扩展上面的实例，重载更多的运算符：</p>
<blockquote>
<h2 id="实例-29"><a href="#实例-29" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace OperatorOvlApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Box</span><br><span class="line">    &#123;</span><br><span class="line">       private double length;      // 长度</span><br><span class="line">       private double breadth;     // 宽度</span><br><span class="line">       private double height;      // 高度</span><br><span class="line">       public double getVolume()</span><br><span class="line">       &#123;</span><br><span class="line">         return length * breadth * height;</span><br><span class="line">       &#125;</span><br><span class="line">      public void setLength( double len )</span><br><span class="line">      &#123;</span><br><span class="line">          length = len;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setBreadth( double bre )</span><br><span class="line">      &#123;</span><br><span class="line">          breadth = bre;</span><br><span class="line">      &#125;</span><br><span class="line">      public void setHeight( double hei )</span><br><span class="line">      &#123;</span><br><span class="line">          height = hei;</span><br><span class="line">      &#125;</span><br><span class="line">      // 重载 + 运算符来把两个 Box 对象相加</span><br><span class="line">      public static Box operator+ (Box b, Box c)</span><br><span class="line">      &#123;</span><br><span class="line">          Box box = new Box();</span><br><span class="line">          box.length = b.length + c.length;</span><br><span class="line">          box.breadth = b.breadth + c.breadth;</span><br><span class="line">          box.height = b.height + c.height;</span><br><span class="line">          return box;</span><br><span class="line">      &#125;</span><br><span class="line">      public static bool operator == (Box lhs, Box rhs)</span><br><span class="line">      &#123;</span><br><span class="line">          bool status = false;</span><br><span class="line">          if (lhs.length == rhs.length &amp;&amp; lhs.height == rhs.height </span><br><span class="line">             &amp;&amp; lhs.breadth == rhs.breadth)</span><br><span class="line">          &#123;</span><br><span class="line">              status = true;</span><br><span class="line">          &#125;</span><br><span class="line">          return status;</span><br><span class="line">      &#125;</span><br><span class="line">      public static bool operator !=(Box lhs, Box rhs)</span><br><span class="line">      &#123;</span><br><span class="line">          bool status = false;</span><br><span class="line">          if (lhs.length != rhs.length || lhs.height != rhs.height </span><br><span class="line">              || lhs.breadth != rhs.breadth)</span><br><span class="line">          &#123;</span><br><span class="line">              status = true;</span><br><span class="line">          &#125;</span><br><span class="line">          return status;</span><br><span class="line">      &#125;</span><br><span class="line">      public static bool operator &lt;(Box lhs, Box rhs)</span><br><span class="line">      &#123;</span><br><span class="line">          bool status = false;</span><br><span class="line">          if (lhs.length &lt; rhs.length &amp;&amp; lhs.height </span><br><span class="line">              &lt; rhs.height &amp;&amp; lhs.breadth &lt; rhs.breadth)</span><br><span class="line">          &#123;</span><br><span class="line">              status = true;</span><br><span class="line">          &#125;</span><br><span class="line">          return status;</span><br><span class="line">      &#125;</span><br><span class="line">      public static bool operator &gt;(Box lhs, Box rhs)</span><br><span class="line">      &#123;</span><br><span class="line">          bool status = false;</span><br><span class="line">          if (lhs.length &gt; rhs.length &amp;&amp; lhs.height </span><br><span class="line">              &gt; rhs.height &amp;&amp; lhs.breadth &gt; rhs.breadth)</span><br><span class="line">          &#123;</span><br><span class="line">              status = true;</span><br><span class="line">          &#125;</span><br><span class="line">          return status;</span><br><span class="line">      &#125;</span><br><span class="line">      public static bool operator &lt;=(Box lhs, Box rhs)</span><br><span class="line">      &#123;</span><br><span class="line">          bool status = false;</span><br><span class="line">          if (lhs.length &lt;= rhs.length &amp;&amp; lhs.height </span><br><span class="line">              &lt;= rhs.height &amp;&amp; lhs.breadth &lt;= rhs.breadth)</span><br><span class="line">          &#123;</span><br><span class="line">              status = true;</span><br><span class="line">          &#125;</span><br><span class="line">          return status;</span><br><span class="line">      &#125;</span><br><span class="line">      public static bool operator &gt;=(Box lhs, Box rhs)</span><br><span class="line">      &#123;</span><br><span class="line">          bool status = false;</span><br><span class="line">          if (lhs.length &gt;= rhs.length &amp;&amp; lhs.height </span><br><span class="line">             &gt;= rhs.height &amp;&amp; lhs.breadth &gt;= rhs.breadth)</span><br><span class="line">          &#123;</span><br><span class="line">              status = true;</span><br><span class="line">          &#125;</span><br><span class="line">          return status;</span><br><span class="line">      &#125;</span><br><span class="line">      public override string ToString()</span><br><span class="line">      &#123;</span><br><span class="line">          return String.Format(&quot;(&#123;0&#125;, &#123;1&#125;, &#123;2&#125;)&quot;, length, breadth, height);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   class Tester</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">        Box Box1 = new Box();          // 声明 Box1，类型为 Box</span><br><span class="line">        Box Box2 = new Box();          // 声明 Box2，类型为 Box</span><br><span class="line">        Box Box3 = new Box();          // 声明 Box3，类型为 Box</span><br><span class="line">        Box Box4 = new Box();</span><br><span class="line">        double volume = 0.0;   // 体积</span><br><span class="line">        // Box1 详述</span><br><span class="line">        Box1.setLength(6.0);</span><br><span class="line">        Box1.setBreadth(7.0);</span><br><span class="line">        Box1.setHeight(5.0);</span><br><span class="line">        // Box2 详述</span><br><span class="line">        Box2.setLength(12.0);</span><br><span class="line">        Box2.setBreadth(13.0);</span><br><span class="line">        Box2.setHeight(10.0);</span><br><span class="line">       // 使用重载的 ToString() 显示两个盒子</span><br><span class="line">        Console.WriteLine(&quot;Box1： &#123;0&#125;&quot;, Box1.ToString());</span><br><span class="line">        Console.WriteLine(&quot;Box2： &#123;0&#125;&quot;, Box2.ToString());</span><br><span class="line">        // Box1 的体积</span><br><span class="line">        volume = Box1.getVolume();</span><br><span class="line">        Console.WriteLine(&quot;Box1 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">        // Box2 的体积</span><br><span class="line">        volume = Box2.getVolume();</span><br><span class="line">        Console.WriteLine(&quot;Box2 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">        // 把两个对象相加</span><br><span class="line">        Box3 = Box1 + Box2;</span><br><span class="line">        Console.WriteLine(&quot;Box3： &#123;0&#125;&quot;, Box3.ToString());</span><br><span class="line">        // Box3 的体积</span><br><span class="line">        volume = Box3.getVolume();</span><br><span class="line">        Console.WriteLine(&quot;Box3 的体积： &#123;0&#125;&quot;, volume);</span><br><span class="line">        //comparing the boxes</span><br><span class="line">        if (Box1 &gt; Box2)</span><br><span class="line">          Console.WriteLine(&quot;Box1 大于 Box2&quot;);</span><br><span class="line">        else</span><br><span class="line">          Console.WriteLine(&quot;Box1 不大于 Box2&quot;);</span><br><span class="line">        if (Box1 &lt; Box2)</span><br><span class="line">          Console.WriteLine(&quot;Box1 小于 Box2&quot;);</span><br><span class="line">        else</span><br><span class="line">          Console.WriteLine(&quot;Box1 不小于 Box2&quot;);</span><br><span class="line">        if (Box1 &gt;= Box2)</span><br><span class="line">          Console.WriteLine(&quot;Box1 大于等于 Box2&quot;);</span><br><span class="line">        else</span><br><span class="line">          Console.WriteLine(&quot;Box1 不大于等于 Box2&quot;);</span><br><span class="line">        if (Box1 &lt;= Box2)</span><br><span class="line">          Console.WriteLine(&quot;Box1 小于等于 Box2&quot;);</span><br><span class="line">        else</span><br><span class="line">          Console.WriteLine(&quot;Box1 不小于等于 Box2&quot;);</span><br><span class="line">        if (Box1 != Box2)</span><br><span class="line">          Console.WriteLine(&quot;Box1 不等于 Box2&quot;);</span><br><span class="line">        else</span><br><span class="line">          Console.WriteLine(&quot;Box1 等于 Box2&quot;);</span><br><span class="line">        Box4 = Box3;</span><br><span class="line">        if (Box3 == Box4)</span><br><span class="line">          Console.WriteLine(&quot;Box3 等于 Box4&quot;);</span><br><span class="line">        else</span><br><span class="line">          Console.WriteLine(&quot;Box3 不等于 Box4&quot;);</span><br><span class="line">        Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Box1： (6, 7, 5)</span><br><span class="line">Box2： (12, 13, 10)</span><br><span class="line">Box1 的体积： 210</span><br><span class="line">Box2 的体积： 1560</span><br><span class="line">Box3： (18, 20, 15)</span><br><span class="line">Box3 的体积： 5400</span><br><span class="line">Box1 不大于 Box2</span><br><span class="line">Box1 小于 Box2</span><br><span class="line">Box1 不大于等于 Box2</span><br><span class="line">Box1 小于等于 Box2</span><br><span class="line">Box1 不等于 Box2</span><br><span class="line">Box3 等于 Box4</span><br></pre></td></tr></table></figure>
<h2 id="二十三-C-接口（Interface）"><a href="#二十三-C-接口（Interface）" class="headerlink" title="二十三. C# 接口（Interface）"></a>二十三. C# 接口（Interface）</h2><p>接口定义了所有类继承接口时应遵循的语法合同。接口定义了语法合同 <strong>“是什么”</strong> 部分，派生类定义了语法合同 <strong>“怎么做”</strong> 部分。</p>
<p>接口定义了属性、方法和事件，这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。</p>
<p>接口使得实现接口的类或结构在形式上保持一致。</p>
<p>抽象类在某种程度上与接口类似，但是，它们大多只是用在当只有少数方法由基类声明由派生类实现时。</p>
<hr>
<h3 id="1-定义接口-MyInterface-cs"><a href="#1-定义接口-MyInterface-cs" class="headerlink" title="1. 定义接口: MyInterface.cs"></a><strong>1. 定义接口: MyInterface.cs</strong></h3><p>接口使用 <strong>interface</strong> 关键字声明，它与类的声明类似。接口声明默认是 public 的。下面是一个接口声明的实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">interface IMyInterface</span><br><span class="line">&#123;</span><br><span class="line">    void MethodToImplement();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上代码定义了接口 IMyInterface。通常接口命令以 I 字母开头，这个接口只有一个方法 MethodToImplement()，没有参数和返回值，当然我们可以按照需求设置参数和返回值。</p>
<p>值得注意的是，该方法并没有具体的实现。</p>
<h3 id="2-接下来我们来实现以上接口：InterfaceImplementer-cs"><a href="#2-接下来我们来实现以上接口：InterfaceImplementer-cs" class="headerlink" title="2. 接下来我们来实现以上接口：InterfaceImplementer.cs"></a><strong>2. 接下来我们来实现以上接口：InterfaceImplementer.cs</strong></h3><blockquote>
<h2 id="实例-30"><a href="#实例-30" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">interface IMyInterface</span><br><span class="line">&#123;</span><br><span class="line">        // 接口成员</span><br><span class="line">    void MethodToImplement();</span><br><span class="line">&#125;</span><br><span class="line">class InterfaceImplementer : IMyInterface</span><br><span class="line">&#123;</span><br><span class="line">    static void Main()</span><br><span class="line">    &#123;</span><br><span class="line">        InterfaceImplementer iImp = new InterfaceImplementer();</span><br><span class="line">        iImp.MethodToImplement();</span><br><span class="line">    &#125;</span><br><span class="line">    public void MethodToImplement()</span><br><span class="line">    &#123;</span><br><span class="line">        Console.WriteLine(&quot;MethodToImplement() called.&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>InterfaceImplementer 类实现了 IMyInterface 接口，接口的实现与类的继承语法格式类似：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">class InterfaceImplementer : IMyInterface</span><br></pre></td></tr></table></figure>
<p>继承接口后，我们需要实现接口的方法 MethodToImplement() , 方法名必须与接口定义的方法名一致。</p>
<hr>
<h3 id="3-接口继承-InterfaceInheritance-cs"><a href="#3-接口继承-InterfaceInheritance-cs" class="headerlink" title="3. 接口继承: InterfaceInheritance.cs"></a><strong>3. 接口继承: InterfaceInheritance.cs</strong></h3><p>以下实例定义了两个接口 IMyInterface 和 IParentInterface。</p>
<p>如果一个接口继承其他接口，那么实现类或结构就需要实现所有接口的成员。</p>
<p>以下实例 IMyInterface 继承了 IParentInterface 接口，因此接口实现类必须实现 MethodToImplement() 和 ParentInterfaceMethod() 方法：</p>
<blockquote>
<h2 id="实例-31"><a href="#实例-31" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">interface IParentInterface</span><br><span class="line">&#123;</span><br><span class="line">    void ParentInterfaceMethod();</span><br><span class="line">&#125;</span><br><span class="line">interface IMyInterface : IParentInterface</span><br><span class="line">&#123;</span><br><span class="line">    void MethodToImplement();</span><br><span class="line">&#125;</span><br><span class="line">class InterfaceImplementer : IMyInterface</span><br><span class="line">&#123;</span><br><span class="line">    static void Main()</span><br><span class="line">    &#123;</span><br><span class="line">        InterfaceImplementer iImp = new InterfaceImplementer();</span><br><span class="line">        iImp.MethodToImplement();</span><br><span class="line">        iImp.ParentInterfaceMethod();</span><br><span class="line">    &#125;</span><br><span class="line">    public void MethodToImplement()</span><br><span class="line">    &#123;</span><br><span class="line">        Console.WriteLine(&quot;MethodToImplement() called.&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public void ParentInterfaceMethod()</span><br><span class="line">    &#123;</span><br><span class="line">        Console.WriteLine(&quot;ParentInterfaceMethod() called.&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实例输出结果为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">MethodToImplement() called.</span><br><span class="line">ParentInterfaceMethod() called.</span><br></pre></td></tr></table></figure>
<h2 id="二十四-C-命名空间（Namespace）"><a href="#二十四-C-命名空间（Namespace）" class="headerlink" title="二十四. C# 命名空间（Namespace）"></a>二十四. C# 命名空间（Namespace）</h2><p><strong>命名空间</strong>的设计目的是提供一种让一组名称与其他名称分隔开的方式。在一个命名空间中声明的类的名称与另一个命名空间中声明的相同的类的名称不冲突。</p>
<h3 id="1-定义命名空间"><a href="#1-定义命名空间" class="headerlink" title="1. 定义命名空间"></a><strong>1. 定义命名空间</strong></h3><p>命名空间的定义是以关键字 <strong>namespace</strong> 开始，后跟命名空间的名称，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">namespace namespace_name</span><br><span class="line">&#123;</span><br><span class="line">   // 代码声明</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>为了调用支持命名空间版本的函数或变量，会把命名空间的名称置于前面，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">namespace_name.item_name;</span><br></pre></td></tr></table></figure>
<p>下面的程序演示了命名空间的用法：</p>
<blockquote>
<h2 id="实例-32"><a href="#实例-32" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace first_space</span><br><span class="line">&#123;</span><br><span class="line">   class namespace_cl</span><br><span class="line">   &#123;</span><br><span class="line">      public void func()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Inside first_space&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">namespace second_space</span><br><span class="line">&#123;</span><br><span class="line">   class namespace_cl</span><br><span class="line">   &#123;</span><br><span class="line">      public void func()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Inside second_space&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;   </span><br><span class="line">class TestClass</span><br><span class="line">&#123;</span><br><span class="line">   static void Main(string[] args)</span><br><span class="line">   &#123;</span><br><span class="line">      first_space.namespace_cl fc = new first_space.namespace_cl();</span><br><span class="line">      second_space.namespace_cl sc = new second_space.namespace_cl();</span><br><span class="line">      fc.func();</span><br><span class="line">      sc.func();</span><br><span class="line">      Console.ReadKey();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Inside first_space</span><br><span class="line">Inside second_space</span><br></pre></td></tr></table></figure>
<h3 id="2-using-关键字"><a href="#2-using-关键字" class="headerlink" title="2. using 关键字"></a><strong><em>2. using</em> 关键字</strong></h3><p><strong>using</strong> 关键字表明程序使用的是给定命名空间中的名称。例如，我们在程序中使用 <strong>System</strong> 命名空间，其中定义了类 Console。我们可以只写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Console.WriteLine (&quot;Hello there&quot;);</span><br></pre></td></tr></table></figure>
<p>我们可以写完全限定名称，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">System.Console.WriteLine(&quot;Hello there&quot;);</span><br></pre></td></tr></table></figure>
<p>您也可以使用 <strong>using</strong> 命名空间指令，这样在使用的时候就不用在前面加上命名空间名称。该指令告诉编译器随后的代码使用了指定命名空间中的名称。下面的代码演示了命名空间的应用。</p>
<p>让我们使用 using 指定重写上面的实例：</p>
<blockquote>
<h2 id="实例-33"><a href="#实例-33" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using first_space;</span><br><span class="line">using second_space;</span><br><span class="line">namespace first_space</span><br><span class="line">&#123;</span><br><span class="line">   class abc</span><br><span class="line">   &#123;</span><br><span class="line">      public void func()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Inside first_space&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">namespace second_space</span><br><span class="line">&#123;</span><br><span class="line">   class efg</span><br><span class="line">   &#123;</span><br><span class="line">      public void func()</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Inside second_space&quot;);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;   </span><br><span class="line">class TestClass</span><br><span class="line">&#123;</span><br><span class="line">   static void Main(string[] args)</span><br><span class="line">   &#123;</span><br><span class="line">      abc fc = new abc();</span><br><span class="line">      efg sc = new efg();</span><br><span class="line">      fc.func();</span><br><span class="line">      sc.func();</span><br><span class="line">      Console.ReadKey();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Inside first_space</span><br><span class="line">Inside second_space</span><br></pre></td></tr></table></figure>
<h3 id="3-嵌套命名空间"><a href="#3-嵌套命名空间" class="headerlink" title="3. 嵌套命名空间"></a><strong>3. 嵌套命名空间</strong></h3><p>命名空间可以被嵌套，即您可以在一个命名空间内定义另一个命名空间，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">namespace namespace_name1 </span><br><span class="line">&#123;</span><br><span class="line">   // 代码声明</span><br><span class="line">   namespace namespace_name2 </span><br><span class="line">   &#123;</span><br><span class="line">     // 代码声明</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>您可以使用点（.）运算符访问嵌套的命名空间的成员，如下所示：</p>
<blockquote>
<h2 id="实例-34"><a href="#实例-34" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using SomeNameSpace;</span><br><span class="line">using SomeNameSpace.Nested;</span><br><span class="line">namespace SomeNameSpace</span><br><span class="line">&#123;</span><br><span class="line">    public class MyClass </span><br><span class="line">    &#123;</span><br><span class="line">        static void Main() </span><br><span class="line">        &#123;</span><br><span class="line">            Console.WriteLine(&quot;In SomeNameSpace&quot;);</span><br><span class="line">            Nested.NestedNameSpaceClass.SayHello();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    // 内嵌命名空间</span><br><span class="line">    namespace Nested   </span><br><span class="line">    &#123;</span><br><span class="line">        public class NestedNameSpaceClass </span><br><span class="line">        &#123;</span><br><span class="line">            public static void SayHello() </span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;In Nested&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">In SomeNameSpace</span><br><span class="line">In Nested</span><br></pre></td></tr></table></figure>
<h2 id="二十五-C-预处理器指令"><a href="#二十五-C-预处理器指令" class="headerlink" title="二十五. C# 预处理器指令"></a>二十五. C# 预处理器指令</h2><p>预处理器指令指导编译器在实际编译开始之前对信息进行预处理。</p>
<p>所有的预处理器指令都是以 # 开始。且在一行上，只有空白字符可以出现在预处理器指令之前。预处理器指令不是语句，所以它们不以分号（;）结束。</p>
<p>C# 编译器没有一个单独的预处理器，但是，指令被处理时就像是有一个单独的预处理器一样。在 C# 中，预处理器指令用于在条件编译中起作用。与 C 和 C++ 不同的是，它们不是用来创建宏。一个预处理器指令必须是该行上的唯一指令。</p>
<h3 id="1-C-预处理器指令列表"><a href="#1-C-预处理器指令列表" class="headerlink" title="1. C# 预处理器指令列表"></a><strong>1. C# 预处理器指令列表</strong></h3><p>下表列出了 C# 中可用的预处理器指令：</p>
<table>
<thead>
<tr>
<th>预处理器指令</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>#define</td>
<td>它用于定义一系列成为符号的字符。</td>
</tr>
<tr>
<td>#undef</td>
<td>它用于取消定义符号。</td>
</tr>
<tr>
<td>#if</td>
<td>它用于测试符号是否为真。</td>
</tr>
<tr>
<td>#else</td>
<td>它用于创建复合条件指令，与 #if 一起使用。</td>
</tr>
<tr>
<td>#elif</td>
<td>它用于创建复合条件指令。</td>
</tr>
<tr>
<td>#endif</td>
<td>指定一个条件指令的结束。</td>
</tr>
<tr>
<td>#line</td>
<td>它可以让您修改编译器的行数以及（可选地）输出错误和警告的文件名。</td>
</tr>
<tr>
<td>#error</td>
<td>它允许从代码的指定位置生成一个错误。</td>
</tr>
<tr>
<td>#warning</td>
<td>它允许从代码的指定位置生成一级警告。</td>
</tr>
<tr>
<td>#region</td>
<td>它可以让您在使用 Visual Studio Code Editor 的大纲特性时，指定一个可展开或折叠的代码块。</td>
</tr>
<tr>
<td>#endregion</td>
<td>它标识着 #region 块的结束。</td>
</tr>
</tbody>
</table>
<h3 id="2-define-预处理器"><a href="#2-define-预处理器" class="headerlink" title="2. #define 预处理器"></a><strong>2. #define 预处理器</strong></h3><p>#define 预处理器指令创建符号常量。</p>
<p>#define 允许您定义一个符号，这样，通过使用符号作为传递给 #if 指令的表达式，表达式将返回 true。它的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">#define symbol</span><br></pre></td></tr></table></figure>
<p>下面的程序说明了这点：</p>
<blockquote>
<h2 id="实例-35"><a href="#实例-35" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">\#define PI </span><br><span class="line">using System;</span><br><span class="line">namespace PreprocessorDAppl</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         #if (PI)</span><br><span class="line">            Console.WriteLine(&quot;PI is defined&quot;);</span><br><span class="line">         #else</span><br><span class="line">            Console.WriteLine(&quot;PI is not defined&quot;);</span><br><span class="line">         #endif</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">PI is defined</span><br></pre></td></tr></table></figure>
<h3 id="3-条件指令"><a href="#3-条件指令" class="headerlink" title="3. 条件指令"></a><strong>3. 条件指令</strong></h3><p>您可以使用 #if 指令来创建一个条件指令。条件指令用于测试符号是否为真。如果为真，编译器会执行 #if 和下一个指令之间的代码。</p>
<p>条件指令的语法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">#if symbol [operator symbol]...</span><br></pre></td></tr></table></figure>
<p>其中，<em>symbol</em> 是要测试的符号名称。您也可以使用 true 和 false，或在符号前放置否定运算符。</p>
<p>常见运算符有：</p>
<ul>
<li>== (等于)</li>
<li>!= (不等于)</li>
<li>&amp;&amp; (与)</li>
<li>|| (或)</li>
</ul>
<p>您也可以用括号把符号和运算符进行分组。条件指令用于在调试版本或编译指定配置时编译代码。一个以 <strong>#if</strong> 指令开始的条件指令，必须显示地以一个 <strong>#endif</strong> 指令终止。</p>
<p>下面的程序演示了条件指令的用法：</p>
<blockquote>
<h2 id="实例-36"><a href="#实例-36" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">define DEBUG</span><br><span class="line"></span><br><span class="line">define VC_V10</span><br><span class="line"></span><br><span class="line">using System;</span><br><span class="line"></span><br><span class="line">public class TestClass</span><br><span class="line"></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">   public static void Main()</span><br><span class="line"></span><br><span class="line">   &#123;</span><br><span class="line"></span><br><span class="line">if (DEBUG &amp;&amp; !VC_V10)</span><br><span class="line"></span><br><span class="line">         Console.WriteLine(&quot;DEBUG is defined&quot;);</span><br><span class="line"></span><br><span class="line">elif (!DEBUG &amp;&amp; VC_V10)</span><br><span class="line"></span><br><span class="line">         Console.WriteLine(&quot;VC_V10 is defined&quot;);</span><br><span class="line"></span><br><span class="line">elif (DEBUG &amp;&amp; VC_V10)</span><br><span class="line"></span><br><span class="line">         Console.WriteLine(&quot;DEBUG and VC_V10 are defined&quot;);</span><br><span class="line"></span><br><span class="line">else</span><br><span class="line"></span><br><span class="line">         Console.WriteLine(&quot;DEBUG and VC_V10 are not defined&quot;);</span><br><span class="line"></span><br><span class="line">endif</span><br><span class="line"></span><br><span class="line">      Console.ReadKey();</span><br><span class="line"></span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">DEBUG and VC_V10 are defined</span><br></pre></td></tr></table></figure>
<p>##二十六. C# 正则表达式</p>
<p><strong>正则表达式</strong> 是一种匹配输入文本的模式。.Net 框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符、运算符和结构组成。</p>
<h3 id="1-定义正则表达式"><a href="#1-定义正则表达式" class="headerlink" title="1. 定义正则表达式"></a>1. 定义正则表达式</h3><p>下面列出了用于定义正则表达式的各种类别的字符、运算符和结构。</p>
<ul>
<li>字符转义</li>
<li>字符类</li>
<li>定位点</li>
<li>分组构造</li>
<li>限定符</li>
<li>反向引用构造</li>
<li>备用构造</li>
<li>替换</li>
<li>杂项构造</li>
</ul>
<h3 id="2-字符转义"><a href="#2-字符转义" class="headerlink" title="2. 字符转义"></a><strong>2. 字符转义</strong></h3><p>正则表达式中的反斜杠字符（\）指示其后跟的字符是特殊字符，或应按原义解释该字符。</p>
<p>下表列出了转义字符：</p>
<table>
<thead>
<tr>
<th>转义字符</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>\a</strong></td>
<td>与报警 (bell) 符 \u0007 匹配。</td>
<td>\a</td>
<td>“Warning!” + ‘\u0007’ 中的 “\u0007”</td>
</tr>
<tr>
<td><strong>\b</strong></td>
<td>在字符类中，与退格键 \u0008 匹配。</td>
<td>[\b]{3,}</td>
<td>“\b\b\b\b” 中的 “\b\b\b\b”</td>
</tr>
<tr>
<td><strong>\t</strong></td>
<td>与制表符 \u0009 匹配。</td>
<td>(\w+)\t</td>
<td>“Name\tAddr\t” 中的 “Name\t” 和 “Addr\t”</td>
</tr>
<tr>
<td><strong>\r</strong></td>
<td>与回车符 \u000D 匹配。（\r 与换行符 \n 不是等效的。）</td>
<td>\r\n(\w+)</td>
<td>“\r\Hello\nWorld.” 中的 “\r\nHello”</td>
</tr>
<tr>
<td><strong>\v</strong></td>
<td>与垂直制表符 \u000B 匹配。</td>
<td>[\v]{2,}</td>
<td>“\v\v\v” 中的 “\v\v\v”</td>
</tr>
<tr>
<td><strong>\f</strong></td>
<td>与换页符 \u000C 匹配。</td>
<td>[\f]{2,}</td>
<td>“\f\f\f” 中的 “\f\f\f”</td>
</tr>
<tr>
<td><strong>\n</strong></td>
<td>与换行符 \u000A 匹配。</td>
<td>\r\n(\w+)</td>
<td>“\r\Hello\nWorld.” 中的 “\r\nHello”</td>
</tr>
<tr>
<td><strong>\e</strong></td>
<td>与转义符 \u001B 匹配。</td>
<td>\e</td>
<td>“\x001B” 中的 “\x001B”</td>
</tr>
<tr>
<td><strong>\ nnn</strong></td>
<td>使用八进制表示形式指定一个字符（nnn 由二到三位数字组成）。</td>
<td>\w\040\w</td>
<td>“a bc d” 中的 “a b” 和 “c d”</td>
</tr>
<tr>
<td><strong>\x nn</strong></td>
<td>使用十六进制表示形式指定字符（nn 恰好由两位数字组成）。</td>
<td>\w\x20\w</td>
<td>“a bc d” 中的 “a b” 和 “c d”</td>
</tr>
<tr>
<td><strong>\c X \c x</strong></td>
<td>匹配 X 或 x 指定的 ASCII 控件字符，其中 X 或 x 是控件字符的字母。</td>
<td>\cC</td>
<td>“\x0003” 中的 “\x0003” (Ctrl-C)</td>
</tr>
<tr>
<td><strong>\u nnnn</strong></td>
<td>使用十六进制表示形式匹配一个 Unicode 字符（由 nnnn 表示的四位数）。</td>
<td>\w\u0020\w</td>
<td>“a bc d” 中的 “a b” 和 “c d”</td>
</tr>
<tr>
<td><strong>\</strong></td>
<td>在后面带有不识别的转义字符时，与该字符匹配。</td>
<td>\d+[+-x*]\d+\d+[+-x*\d+</td>
<td>“(2+2) <em> 3</em>9” 中的 “2+2” 和 “3*9”</td>
</tr>
</tbody>
</table>
<h3 id="3-字符类"><a href="#3-字符类" class="headerlink" title="3. 字符类"></a><strong>3. 字符类</strong></h3><p>字符类与一组字符中的任何一个字符匹配。</p>
<p>下表列出了字符类：</p>
<table>
<thead>
<tr>
<th>字符类</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>[character_group]</strong></td>
<td>匹配 character_group 中的任何单个字符。 默认情况下，匹配区分大小写。</td>
<td>[mn]</td>
<td>“mat” 中的 “m”，”moon” 中的 “m” 和 “n”</td>
</tr>
<tr>
<td><strong>[^character_group]</strong></td>
<td>非：与不在 character_group 中的任何单个字符匹配。 默认情况下，character_group 中的字符区分大小写。</td>
<td>[^aei]</td>
<td>“avail” 中的 “v” 和 “l”</td>
</tr>
<tr>
<td><strong>[ first - last ]</strong></td>
<td>字符范围：与从 first 到 last 的范围中的任何单个字符匹配。</td>
<td>[b-d]</td>
<td>[b-d]irds 可以匹配 Birds、 Cirds、 Dirds</td>
</tr>
<tr>
<td><strong>.</strong></td>
<td>通配符：与除 \n 之外的任何单个字符匹配。 若要匹配原意句点字符（. 或 \u002E），您必须在该字符前面加上转义符 (.)。</td>
<td>a.e</td>
<td>“have” 中的 “ave”， “mate” 中的 “ate”</td>
</tr>
<tr>
<td><strong>\p{ name }</strong></td>
<td>与 <em>name</em> 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。</td>
<td>\p{Lu}</td>
<td>“City Lights” 中的 “C” 和 “L”</td>
</tr>
<tr>
<td><strong>\P{ name }</strong></td>
<td>与不在 <em>name</em> 指定的 Unicode 通用类别或命名块中的任何单个字符匹配。</td>
<td>\P{Lu}</td>
<td>“City” 中的 “i”、 “t” 和 “y”</td>
</tr>
<tr>
<td><strong>\w</strong></td>
<td>与任何单词字符匹配。</td>
<td>\w</td>
<td>“Room#1” 中的 “R”、 “o”、 “m” 和 “1”</td>
</tr>
<tr>
<td><strong>\W</strong></td>
<td>与任何非单词字符匹配。</td>
<td>\W</td>
<td>“Room#1” 中的 “#”</td>
</tr>
<tr>
<td><strong>\s</strong></td>
<td>与任何空白字符匹配。</td>
<td>\w\s</td>
<td>“ID A1.3” 中的 “D “</td>
</tr>
<tr>
<td><strong>\S</strong></td>
<td>与任何非空白字符匹配。</td>
<td>\s\S</td>
<td>“int __ctr” 中的 “ _”</td>
</tr>
<tr>
<td><strong>\d</strong></td>
<td>与任何十进制数字匹配。</td>
<td>\d</td>
<td>“4 = IV” 中的 “4”</td>
</tr>
<tr>
<td><strong>\D</strong></td>
<td>匹配不是十进制数的任意字符。</td>
<td>\D</td>
<td>“4 = IV” 中的 “ “、 “=”、 “ “、 “I” 和 “V”</td>
</tr>
</tbody>
</table>
<h3 id="4-定位点"><a href="#4-定位点" class="headerlink" title="4. 定位点"></a><strong>4. 定位点</strong></h3><p>定位点或原子零宽度断言会使匹配成功或失败，具体取决于字符串中的当前位置，但它们不会使引擎在字符串中前进或使用字符。</p>
<p>下表列出了定位点：</p>
<table>
<thead>
<tr>
<th>断言</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>^</strong></td>
<td>匹配必须从字符串或一行的开头开始。</td>
<td>^\d{3}</td>
<td>“567-777-“ 中的 “567”</td>
</tr>
<tr>
<td><strong>$</strong></td>
<td>匹配必须出现在字符串的末尾或出现在行或字符串末尾的 <strong>\n</strong> 之前。</td>
<td>-\d{4}$</td>
<td>“8-12-2012” 中的 “-2012”</td>
</tr>
<tr>
<td><strong>\A</strong></td>
<td>匹配必须出现在字符串的开头。</td>
<td>\A\w{4}</td>
<td>“Code-007-“ 中的 “Code”</td>
</tr>
<tr>
<td><strong>\Z</strong></td>
<td>匹配必须出现在字符串的末尾或出现在字符串末尾的 <strong>\n</strong>之前。</td>
<td>-\d{3}\Z</td>
<td>“Bond-901-007” 中的 “-007”</td>
</tr>
<tr>
<td><strong>\z</strong></td>
<td>匹配必须出现在字符串的末尾。</td>
<td>-\d{3}\z</td>
<td>“-901-333” 中的 “-333”</td>
</tr>
<tr>
<td><strong>\G</strong></td>
<td>匹配必须出现在上一个匹配结束的地方。</td>
<td>\G(\d)</td>
<td>“(1)(3)(5)<a href="9">7</a>“ 中的 “(1)”、 “(3)” 和 “(5)”</td>
</tr>
<tr>
<td><strong>\b</strong></td>
<td>匹配一个单词边界，也就是指单词和空格间的位置。</td>
<td>er\b</td>
<td>匹配”never”中的”er”，但不能匹配”verb”中的”er”。</td>
</tr>
<tr>
<td><strong>\B</strong></td>
<td>匹配非单词边界。</td>
<td>er\B</td>
<td>匹配”verb”中的”er”，但不能匹配”never”中的”er”。</td>
</tr>
</tbody>
</table>
<h3 id="5-分组构造"><a href="#5-分组构造" class="headerlink" title="5. 分组构造"></a><strong>5. 分组构造</strong></h3><p>分组构造描述了正则表达式的子表达式，通常用于捕获输入字符串的子字符串。</p>
<p>下表列出了分组构造：</p>
<table>
<thead>
<tr>
<th>分组构造</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>( subexpression )</strong></td>
<td>捕获匹配的子表达式并将其分配到一个从零开始的序号中。</td>
<td>(\w)\1</td>
<td>“deep” 中的 “ee”</td>
</tr>
<tr>
<td><strong>(?&lt; name &gt;subexpression)</strong></td>
<td>将匹配的子表达式捕获到一个命名组中。</td>
<td>(?&lt; double&gt;\w)\k&lt; double&gt;</td>
<td>“deep” 中的 “ee”</td>
</tr>
<tr>
<td><strong>(?&lt; name1 -name2 &gt;subexpression)</strong></td>
<td>定义平衡组定义。</td>
<td>(((?’Open’()[^()]<em>)+((?’Close-Open’))[^()]</em>)+)*(?(Open)(?!))$</td>
<td>“3+2^((1-3)<em>(3-1))” 中的 “((1-3)</em>(3-1))”</td>
</tr>
<tr>
<td><strong>(?: subexpression)</strong></td>
<td>定义非捕获组。</td>
<td>Write(?:Line)?</td>
<td>“Console.WriteLine()” 中的 “WriteLine”</td>
</tr>
<tr>
<td><strong>(?imnsx-imnsx:subexpression)</strong></td>
<td>应用或禁用 <em>subexpression</em> 中指定的选项。</td>
<td>A\d{2}(?i:\w+)\b</td>
<td>“A12xl A12XL a12xl” 中的 “A12xl” 和 “A12XL”</td>
</tr>
<tr>
<td><strong>(?= subexpression)</strong></td>
<td>零宽度正预测先行断言。</td>
<td>\w+(?=.)</td>
<td>“He is. The dog ran. The sun is out.” 中的 “is”、 “ran” 和 “out”</td>
</tr>
<tr>
<td><strong>(?! subexpression)</strong></td>
<td>零宽度负预测先行断言。</td>
<td>\b(?!un)\w+\b</td>
<td>“unsure sure unity used” 中的 “sure” 和 “used”</td>
</tr>
<tr>
<td><strong>(?&lt;=subexpression)</strong></td>
<td>零宽度正回顾后发断言。</td>
<td>(?&lt;=19)\d{2}\b</td>
<td>“1851 1999 1950 1905 2003” 中的 “99”、”50”和 “05”</td>
</tr>
<tr>
<td><strong>(?&lt;! subexpression)</strong></td>
<td>零宽度负回顾后发断言。</td>
<td>(?</td>
<td>“Hi woman Hi man” 中的 “man”</td>
</tr>
<tr>
<td><strong>(?&gt; subexpression)</strong></td>
<td>非回溯（也称为”贪婪”）子表达式。</td>
<td><a href="?&gt;A+B+">13579</a></td>
<td>“1ABB 3ABBC 5AB 5AC” 中的 “1ABB”、 “3ABB” 和 “5AB”</td>
</tr>
</tbody>
</table>
<blockquote>
<h2 id="实例-37"><a href="#实例-37" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.Text.RegularExpressions;</span><br><span class="line">public class Example</span><br><span class="line">&#123;</span><br><span class="line">   public static void Main()</span><br><span class="line">   &#123;</span><br><span class="line">      string input = &quot;1851 1999 1950 1905 2003&quot;;</span><br><span class="line">      string pattern = @&quot;(?&lt;=19)\d&#123;2&#125;\b&quot;;</span><br><span class="line">      foreach (Match match in Regex.Matches(input, pattern))</span><br><span class="line">         Console.WriteLine(match.Value);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行实例 »</p>
<p>###<strong>6.  限定符</strong></p>
<p>限定符指定在输入字符串中必须存在上一个元素（可以是字符、组或字符类）的多少个实例才能出现匹配项。 限定符包括下表中列出的语言元素。</p>
<p>下表列出了限定符：</p>
<table>
<thead>
<tr>
<th>限定符</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>*</strong></td>
<td>匹配上一个元素零次或多次。</td>
<td>\d*.\d</td>
<td>“.0”、 “19.9”、 “219.9”</td>
</tr>
<tr>
<td><strong>+</strong></td>
<td>匹配上一个元素一次或多次。</td>
<td>“be+”</td>
<td>“been” 中的 “bee”， “bent” 中的 “be”</td>
</tr>
<tr>
<td><strong>?</strong></td>
<td>匹配上一个元素零次或一次。</td>
<td>“rai?n”</td>
<td>“ran”、 “rain”</td>
</tr>
<tr>
<td><strong>{ n }</strong></td>
<td>匹配上一个元素恰好 n 次。</td>
<td>“,\d{3}”</td>
<td>“1,043.6” 中的 “,043”， “9,876,543,210” 中的 “,876”、 “,543” 和 “,210”</td>
</tr>
<tr>
<td><strong>{ n ,}</strong></td>
<td>匹配上一个元素至少 n 次。</td>
<td>“\d{2,}”</td>
<td>“166”、 “29”、 “1930”</td>
</tr>
<tr>
<td><strong>{ n , m }</strong></td>
<td>匹配上一个元素至少 n 次，但不多于 m 次。</td>
<td>“\d{3,5}”</td>
<td>“166”， “17668”， “193024” 中的 “19302”</td>
</tr>
<tr>
<td><strong>*?</strong></td>
<td>匹配上一个元素零次或多次，但次数尽可能少。</td>
<td>\d*?.\d</td>
<td>“.0”、 “19.9”、 “219.9”</td>
</tr>
<tr>
<td><strong>+?</strong></td>
<td>匹配上一个元素一次或多次，但次数尽可能少。</td>
<td>“be+?”</td>
<td>“been” 中的 “be”， “bent” 中的 “be”</td>
</tr>
<tr>
<td><strong>??</strong></td>
<td>匹配上一个元素零次或一次，但次数尽可能少。</td>
<td>“rai??n”</td>
<td>“ran”、 “rain”</td>
</tr>
<tr>
<td><strong>{ n }?</strong></td>
<td>匹配前导元素恰好 n 次。</td>
<td>“,\d{3}?”</td>
<td>“1,043.6” 中的 “,043”， “9,876,543,210” 中的 “,876”、 “,543” 和 “,210”</td>
</tr>
<tr>
<td><strong>{ n ,}?</strong></td>
<td>匹配上一个元素至少 n 次，但次数尽可能少。</td>
<td>“\d{2,}?”</td>
<td>“166”、 “29” 和 “1930”</td>
</tr>
<tr>
<td><strong>{ n , m }?</strong></td>
<td>匹配上一个元素的次数介于 n 和 m 之间，但次数尽可能少。</td>
<td>“\d{3,5}?”</td>
<td>“166”， “17668”， “193024” 中的 “193” 和 “024”</td>
</tr>
</tbody>
</table>
<h3 id="7-反向引用构造"><a href="#7-反向引用构造" class="headerlink" title="7. 反向引用构造"></a><strong>7. 反向引用构造</strong></h3><p>反向引用允许在同一正则表达式中随后标识以前匹配的子表达式。</p>
<p>下表列出了反向引用构造：</p>
<table>
<thead>
<tr>
<th>反向引用构造</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>\ number</strong></td>
<td>反向引用。 匹配编号子表达式的值。</td>
<td>(\w)\1</td>
<td>“seek” 中的 “ee”</td>
</tr>
<tr>
<td><strong>\k&lt; name &gt;</strong></td>
<td>命名反向引用。 匹配命名表达式的值。</td>
<td>(?&lt; char&gt;\w)\k&lt; char&gt;</td>
<td>“seek” 中的 “ee”</td>
</tr>
</tbody>
</table>
<h3 id="8-备用构造"><a href="#8-备用构造" class="headerlink" title="8. 备用构造"></a><strong>8. 备用构造</strong></h3><p>备用构造用于修改正则表达式以启用 either/or 匹配。</p>
<p>下表列出了备用构造：</p>
<table>
<thead>
<tr>
<th>备用构造</th>
<th>描述</th>
<th>模式</th>
<th>匹配</th>
</tr>
</thead>
<tbody>
<tr>
<td>**\</td>
<td>**</td>
<td>匹配以竖线 (\</td>
<td>) 字符分隔的任何一个元素。</td>
<td>th(e\</td>
<td>is\</td>
<td>at)</td>
<td>“this is the day. “ 中的 “the” 和 “this”</td>
</tr>
<tr>
<td>**(?( expression )yes \</td>
<td>no )**</td>
<td>如果正则表达式模式由 expression 匹配指定，则匹配 <em>yes</em>；否则匹配可选的 <em>no</em>部分。 expression 被解释为零宽度断言。</td>
<td>(?(A)A\d{2}\b\</td>
<td>\b\d{3}\b)</td>
<td>“A10 C103 910” 中的 “A10” 和 “910”</td>
</tr>
<tr>
<td>**(?( name )yes \</td>
<td>no )**</td>
<td>如果 name 或已命名或已编号的捕获组具有匹配，则匹配 <em>yes</em>；否则匹配可选的 <em>no</em>。</td>
<td>(?&lt; quoted&gt;”)?(?(quoted).+?”\</td>
<td>\S+\s)</td>
<td>“Dogs.jpg “Yiska playing.jpg”” 中的 Dogs.jpg 和 “Yiska playing.jpg”</td>
</tr>
</tbody>
</table>
<h3 id="9-替换"><a href="#9-替换" class="headerlink" title="9. 替换"></a><strong>9. 替换</strong></h3><p>替换是替换模式中使用的正则表达式。</p>
<p>下表列出了用于替换的字符：</p>
<table>
<thead>
<tr>
<th>字符</th>
<th>描述</th>
<th>模式</th>
<th>替换模式</th>
<th>输入字符串</th>
<th>结果字符串</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>$</strong>number</td>
<td>替换按组 <em>number</em> 匹配的子字符串。</td>
<td>\b(\w+)(\s)(\w+)\b</td>
<td>$3$2$1</td>
<td>“one two”</td>
<td>“two one”</td>
</tr>
<tr>
<td><strong>${</strong>name<strong>}</strong></td>
<td>替换按命名组 <em>name</em> 匹配的子字符串。</td>
<td>\b(?&lt; word1&gt;\w+)(\s)(?&lt; word2&gt;\w+)\b</td>
<td>${word2} ${word1}</td>
<td>“one two”</td>
<td>“two one”</td>
</tr>
<tr>
<td><strong>$$</strong></td>
<td>替换字符”$”。</td>
<td>\b(\d+)\s?USD</td>
<td>$$$1</td>
<td>“103 USD”</td>
<td>“$103”</td>
</tr>
<tr>
<td><strong>$&amp;</strong></td>
<td>替换整个匹配项的一个副本。</td>
<td>(\$<em>(\d</em>(.+\d+)?){1})</td>
<td>**$&amp;</td>
<td>“$1.30”</td>
<td>“<strong>$1.30</strong>“</td>
</tr>
<tr>
<td><strong>$`</strong></td>
<td>替换匹配前的输入字符串的所有文本。</td>
<td>B+</td>
<td>$`</td>
<td>“AABBCC”</td>
<td>“AAAACC”</td>
</tr>
<tr>
<td><strong>$’</strong></td>
<td>替换匹配后的输入字符串的所有文本。</td>
<td>B+</td>
<td>$’</td>
<td>“AABBCC”</td>
<td>“AACCCC”</td>
</tr>
<tr>
<td><strong>$+</strong></td>
<td>替换最后捕获的组。</td>
<td>B+(C+)</td>
<td>$+</td>
<td>“AABBCCDD”</td>
<td>AACCDD</td>
</tr>
<tr>
<td><strong>$_</strong></td>
<td>替换整个输入字符串。</td>
<td>B+</td>
<td>$_</td>
<td>“AABBCC”</td>
<td>“AAAABBCCCC”</td>
</tr>
</tbody>
</table>
<h3 id="10-杂项构造"><a href="#10-杂项构造" class="headerlink" title="10. 杂项构造"></a><strong>10. 杂项构造</strong></h3><p>下表列出了各种杂项构造：</p>
<table>
<thead>
<tr>
<th>构造</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>(?imnsx-imnsx)</strong></td>
<td>在模式中间对诸如不区分大小写这样的选项进行设置或禁用。</td>
<td>\bA(?i)b\w+\b 匹配 “ABA Able Act” 中的 “ABA” 和 “Able”</td>
</tr>
<tr>
<td><strong>(?#注释)</strong></td>
<td>内联注释。该注释在第一个右括号处终止。</td>
<td>\bA(?#匹配以A开头的单词)\w+\b</td>
</tr>
<tr>
<td><strong>#</strong> [行尾]</td>
<td>该注释以非转义的 # 开头，并继续到行的结尾。</td>
<td>(?x)\bA\w+\b#匹配以 A 开头的单词</td>
</tr>
</tbody>
</table>
<p>###<strong>11. Regex 类</strong></p>
<p>Regex 类用于表示一个正则表达式。</p>
<p>下表列出了 Regex 类中一些常用的方法：</p>
<table>
<thead>
<tr>
<th>序号</th>
<th>方法 &amp; 描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><strong>public bool IsMatch( string input )</strong> 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。</td>
</tr>
<tr>
<td>2</td>
<td><strong>public bool IsMatch( string input, int startat )</strong> 指示 Regex 构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项，从字符串中指定的开始位置开始。</td>
</tr>
<tr>
<td>3</td>
<td><strong>public static bool IsMatch( string input, string pattern )</strong> 指示指定的正则表达式是否在指定的输入字符串中找到匹配项。</td>
</tr>
<tr>
<td>4</td>
<td><strong>public MatchCollection Matches( string input )</strong> 在指定的输入字符串中搜索正则表达式的所有匹配项。</td>
</tr>
<tr>
<td>5</td>
<td><strong>public string Replace( string input, string replacement )</strong> 在指定的输入字符串中，把所有匹配正则表达式模式的所有匹配的字符串替换为指定的替换字符串。</td>
</tr>
<tr>
<td>6</td>
<td><strong>public string[] Split( string input )</strong> 把输入字符串分割为子字符串数组，根据在 Regex 构造函数中指定的正则表达式模式定义的位置进行分割。</td>
</tr>
</tbody>
</table>
<p>如需了解 Regex 类的完整的属性列表，请参阅微软的 C# 文档。</p>
<blockquote>
<h2 id="实例-1"><a href="#实例-1" class="headerlink" title="实例 1"></a>实例 1</h2></blockquote>
<p>下面的实例匹配了以 ‘S’ 开头的单词：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.Text.RegularExpressions;</span><br><span class="line">namespace RegExApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      private static void showMatch(string text, string expr)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;The Expression: &quot; + expr);</span><br><span class="line">         MatchCollection mc = Regex.Matches(text, expr);</span><br><span class="line">         foreach (Match m in mc)</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(m);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         string str = &quot;A Thousand Splendid Suns&quot;;</span><br><span class="line">         Console.WriteLine(&quot;Matching words that start with &apos;S&apos;: &quot;);</span><br><span class="line">         showMatch(str, @&quot;\bS\S*&quot;);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Matching words that start with &apos;S&apos;:</span><br><span class="line">The Expression: \bS\S*</span><br><span class="line">Splendid</span><br><span class="line">Suns</span><br></pre></td></tr></table></figure>
<blockquote>
<h2 id="实例-2"><a href="#实例-2" class="headerlink" title="实例 2"></a>实例 2</h2></blockquote>
<p>下面的实例匹配了以 ‘m’ 开头以 ‘e’ 结尾的单词：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.Text.RegularExpressions;</span><br><span class="line">namespace RegExApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      private static void showMatch(string text, string expr)</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;The Expression: &quot; + expr);</span><br><span class="line">         MatchCollection mc = Regex.Matches(text, expr);</span><br><span class="line">         foreach (Match m in mc)</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(m);</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         string str = &quot;make maze and manage to measure it&quot;;</span><br><span class="line">         Console.WriteLine(&quot;Matching words start with &apos;m&apos; and ends with &apos;e&apos;:&quot;);</span><br><span class="line">         showMatch(str, @&quot;\bm\S*e\b&quot;);</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Matching words start with &apos;m&apos; and ends with &apos;e&apos;:</span><br><span class="line">The Expression: \bm\S*e\b</span><br><span class="line">make</span><br><span class="line">maze</span><br><span class="line">manage</span><br><span class="line">measure</span><br></pre></td></tr></table></figure>
<blockquote>
<h2 id="实例-3"><a href="#实例-3" class="headerlink" title="实例 3"></a>实例 3</h2></blockquote>
<p>下面的实例替换掉多余的空格：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.Text.RegularExpressions;</span><br><span class="line">namespace RegExApplication</span><br><span class="line">&#123;</span><br><span class="line">   class Program</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         string input = &quot;Hello   World   &quot;;</span><br><span class="line">         string pattern = &quot;\\s+&quot;;</span><br><span class="line">         string replacement = &quot; &quot;;</span><br><span class="line">         Regex rgx = new Regex(pattern);</span><br><span class="line">         string result = rgx.Replace(input, replacement);</span><br><span class="line">         Console.WriteLine(&quot;Original String: &#123;0&#125;&quot;, input);</span><br><span class="line">         Console.WriteLine(&quot;Replacement String: &#123;0&#125;&quot;, result);    </span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Original String: Hello   World   </span><br><span class="line">Replacement String: Hello World</span><br></pre></td></tr></table></figure>
<h2 id="二十七-C-异常处理"><a href="#二十七-C-异常处理" class="headerlink" title="二十七. C# 异常处理"></a>二十七. C# 异常处理</h2><p>异常是在程序执行期间出现的问题。C# 中的异常是对程序运行时出现的特殊情况的一种响应，比如尝试除以零。</p>
<p>异常提供了一种把程序控制权从某个部分转移到另一个部分的方式。C# 异常处理时建立在四个关键词之上的：<strong>try</strong>、<strong>catch</strong>、<strong>finally</strong> 和 <strong>throw</strong>。</p>
<ul>
<li><strong>try</strong>：一个 try 块标识了一个将被激活的特定的异常的代码块。后跟一个或多个 catch 块。</li>
<li><strong>catch</strong>：程序通过异常处理程序捕获异常。catch 关键字表示异常的捕获。</li>
<li><strong>finally</strong>：finally 块用于执行给定的语句，不管异常是否被抛出都会执行。例如，如果您打开一个文件，不管是否出现异常文件都要被关闭。</li>
<li><strong>throw</strong>：当问题出现时，程序抛出一个异常。使用 throw 关键字来完成。</li>
</ul>
<h3 id="1-语法"><a href="#1-语法" class="headerlink" title="1.  语法"></a><strong>1.  语法</strong></h3><p>假设一个块将出现异常，一个方法使用 try 和 catch 关键字捕获异常。try/catch 块内的代码为受保护的代码，使用 try/catch 语法如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">try</span><br><span class="line">&#123;</span><br><span class="line">   // 引起异常的语句</span><br><span class="line">&#125;</span><br><span class="line">catch( ExceptionName e1 )</span><br><span class="line">&#123;</span><br><span class="line">   // 错误处理代码</span><br><span class="line">&#125;</span><br><span class="line">catch( ExceptionName e2 )</span><br><span class="line">&#123;</span><br><span class="line">   // 错误处理代码</span><br><span class="line">&#125;</span><br><span class="line">catch( ExceptionName eN )</span><br><span class="line">&#123;</span><br><span class="line">   // 错误处理代码</span><br><span class="line">&#125;</span><br><span class="line">finally</span><br><span class="line">&#123;</span><br><span class="line">   // 要执行的语句</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>您可以列出多个 catch 语句捕获不同类型的异常，以防 try 块在不同的情况下生成多个异常。</p>
<h3 id="2-C-中的异常类"><a href="#2-C-中的异常类" class="headerlink" title="2. C# 中的异常类"></a><strong>2. C# 中的异常类</strong></h3><p>C# 异常是使用类来表示的。C# 中的异常类主要是直接或间接地派生于 <strong>System.Exception</strong> 类。<strong>System.ApplicationException</strong> 和 <strong>System.SystemException</strong> 类是派生于 System.Exception 类的异常类。</p>
<p><strong>System.ApplicationException</strong> 类支持由应用程序生成的异常。所以程序员定义的异常都应派生自该类。</p>
<p><strong>System.SystemException</strong> 类是所有预定义的系统异常的基类。</p>
<p>下表列出了一些派生自 Sytem.SystemException 类的预定义的异常类：</p>
<table>
<thead>
<tr>
<th>异常类</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>System.IO.IOException</td>
<td>处理 I/O 错误。</td>
</tr>
<tr>
<td>System.IndexOutOfRangeException</td>
<td>处理当方法指向超出范围的数组索引时生成的错误。</td>
</tr>
<tr>
<td>System.ArrayTypeMismatchException</td>
<td>处理当数组类型不匹配时生成的错误。</td>
</tr>
<tr>
<td>System.NullReferenceException</td>
<td>处理当依从一个空对象时生成的错误。</td>
</tr>
<tr>
<td>System.DivideByZeroException</td>
<td>处理当除以零时生成的错误。</td>
</tr>
<tr>
<td>System.InvalidCastException</td>
<td>处理在类型转换期间生成的错误。</td>
</tr>
<tr>
<td>System.OutOfMemoryException</td>
<td>处理空闲内存不足生成的错误。</td>
</tr>
<tr>
<td>System.StackOverflowException</td>
<td>处理栈溢出生成的错误。</td>
</tr>
</tbody>
</table>
<h3 id="3-异常处理"><a href="#3-异常处理" class="headerlink" title="3. 异常处理"></a><strong>3. 异常处理</strong></h3><p>C# 以 try 和 catch 块的形式提供了一种结构化的异常处理方案。使用这些块，把核心程序语句与错误处理语句分离开。</p>
<p>这些错误处理块是使用 <strong>try</strong>、<strong>catch</strong> 和 <strong>finally</strong> 关键字实现的。下面是一个当除以零时抛出异常的实例：</p>
<blockquote>
<p> 实例</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace ErrorHandlingApplication</span><br><span class="line">&#123;</span><br><span class="line">    class DivNumbers</span><br><span class="line">    &#123;</span><br><span class="line">        int result;</span><br><span class="line">        DivNumbers()</span><br><span class="line">        &#123;</span><br><span class="line">            result = 0;</span><br><span class="line">        &#125;</span><br><span class="line">        public void division(int num1, int num2)</span><br><span class="line">        &#123;</span><br><span class="line">            try</span><br><span class="line">            &#123;</span><br><span class="line">                result = num1 / num2;</span><br><span class="line">            &#125;</span><br><span class="line">            catch (DivideByZeroException e)</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Exception caught: &#123;0&#125;&quot;, e);</span><br><span class="line">            &#125;</span><br><span class="line">            finally</span><br><span class="line">            &#123;</span><br><span class="line">                Console.WriteLine(&quot;Result: &#123;0&#125;&quot;, result);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            DivNumbers d = new DivNumbers();</span><br><span class="line">            d.division(25, 0);</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Exception caught: System.DivideByZeroException: Attempted to divide by zero. </span><br><span class="line">at ...</span><br><span class="line">Result: 0</span><br></pre></td></tr></table></figure>
<h3 id="4-创建用户自定义异常"><a href="#4-创建用户自定义异常" class="headerlink" title="4. 创建用户自定义异常"></a><strong>4. 创建用户自定义异常</strong></h3><p>您也可以定义自己的异常。用户自定义的异常类是派生自 <strong>ApplicationException</strong> 类。下面的实例演示了这点：</p>
<blockquote>
<h2 id="实例-38"><a href="#实例-38" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">namespace UserDefinedException</span><br><span class="line">&#123;</span><br><span class="line">   class TestTemperature</span><br><span class="line">   &#123;</span><br><span class="line">      static void Main(string[] args)</span><br><span class="line">      &#123;</span><br><span class="line">         Temperature temp = new Temperature();</span><br><span class="line">         try</span><br><span class="line">         &#123;</span><br><span class="line">            temp.showTemp();</span><br><span class="line">         &#125;</span><br><span class="line">         catch(TempIsZeroException e)</span><br><span class="line">         &#123;</span><br><span class="line">            Console.WriteLine(&quot;TempIsZeroException: &#123;0&#125;&quot;, e.Message);</span><br><span class="line">         &#125;</span><br><span class="line">         Console.ReadKey();</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">public class TempIsZeroException: ApplicationException</span><br><span class="line">&#123;</span><br><span class="line">   public TempIsZeroException(string message): base(message)</span><br><span class="line">   &#123;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">public class Temperature</span><br><span class="line">&#123;</span><br><span class="line">   int temperature = 0;</span><br><span class="line">   public void showTemp()</span><br><span class="line">   &#123;</span><br><span class="line">      if(temperature == 0)</span><br><span class="line">      &#123;</span><br><span class="line">         throw (new TempIsZeroException(&quot;Zero Temperature found&quot;));</span><br><span class="line">      &#125;</span><br><span class="line">      else</span><br><span class="line">      &#123;</span><br><span class="line">         Console.WriteLine(&quot;Temperature: &#123;0&#125;&quot;, temperature);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">TempIsZeroException: Zero Temperature found</span><br></pre></td></tr></table></figure>
<p><strong>5. 抛出对象</strong></p>
<p>如果异常是直接或间接派生自 <strong>System.Exception</strong> 类，您可以抛出一个对象。您可以在 catch 块中使用 throw 语句来抛出当前的对象，如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Catch(Exception e)</span><br><span class="line">&#123;</span><br><span class="line">   ...</span><br><span class="line">   Throw e</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="二十八-C-文件的输入与输出"><a href="#二十八-C-文件的输入与输出" class="headerlink" title="二十八. C#文件的输入与输出"></a>二十八. C#文件的输入与输出</h2><p>一个 <strong>文件</strong> 是一个存储在磁盘中带有指定名称和目录路径的数据集合。当打开文件进行读写时，它变成一个 <strong>流</strong>。</p>
<p>从根本上说，流是通过通信路径传递的字节序列。有两个主要的流：<strong>输入流</strong> 和 <strong>输出流</strong>。<strong>输入流</strong>用于从文件读取数据（读操作），<strong>输出流</strong>用于向文件写入数据（写操作）。</p>
<h3 id="1-C-I-O-类"><a href="#1-C-I-O-类" class="headerlink" title="1. C# I/O 类"></a>1. C# I/O 类</h3><p>System.IO 命名空间有各种不同的类，用于执行各种文件操作，如创建和删除文件、读取或写入文件，关闭文件等。</p>
<p>下表列出了一些 System.IO 命名空间中常用的非抽象类：</p>
<table>
<thead>
<tr>
<th>I/O 类</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>BinaryReader</td>
<td>从二进制流读取原始数据。</td>
</tr>
<tr>
<td>BinaryWriter</td>
<td>以二进制格式写入原始数据。</td>
</tr>
<tr>
<td>BufferedStream</td>
<td>字节流的临时存储。</td>
</tr>
<tr>
<td>Directory</td>
<td>有助于操作目录结构。</td>
</tr>
<tr>
<td>DirectoryInfo</td>
<td>用于对目录执行操作。</td>
</tr>
<tr>
<td>DriveInfo</td>
<td>提供驱动器的信息。</td>
</tr>
<tr>
<td>File</td>
<td>有助于处理文件。</td>
</tr>
<tr>
<td>FileInfo</td>
<td>用于对文件执行操作。</td>
</tr>
<tr>
<td>FileStream</td>
<td>用于文件中任何位置的读写。</td>
</tr>
<tr>
<td>MemoryStream</td>
<td>用于随机访问存储在内存中的数据流。</td>
</tr>
<tr>
<td>Path</td>
<td>对路径信息执行操作。</td>
</tr>
<tr>
<td>StreamReader</td>
<td>用于从字节流中读取字符。</td>
</tr>
<tr>
<td>StreamWriter</td>
<td>用于向一个流中写入字符。</td>
</tr>
<tr>
<td>StringReader</td>
<td>用于读取字符串缓冲区。</td>
</tr>
<tr>
<td>StringWriter</td>
<td>用于写入字符串缓冲区。</td>
</tr>
</tbody>
</table>
<h3 id="2-FileStream-类"><a href="#2-FileStream-类" class="headerlink" title="2. FileStream 类"></a><strong>2. FileStream 类</strong></h3><p>System.IO 命名空间中的 <strong>FileStream</strong> 类有助于文件的读写与关闭。该类派生自抽象类 Stream。</p>
<p>您需要创建一个 <strong>FileStream</strong> 对象来创建一个新的文件，或打开一个已有的文件。创建 <strong>FileStream</strong> 对象的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">FileStream &lt;object_name&gt; = new FileStream( &lt;file_name&gt;,</span><br><span class="line">&lt;FileMode Enumerator&gt;, &lt;FileAccess Enumerator&gt;, &lt;FileShare Enumerator&gt;);</span><br></pre></td></tr></table></figure>
<p>例如，创建一个 FileStream 对象 <strong>F</strong> 来读取名为 <strong>sample.txt</strong> 的文件：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FileStream F = new FileStream(&quot;sample.txt&quot;, FileMode.Open, FileAccess.Read, FileShare.Read);</span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th>参数</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>FileMode</td>
<td><strong>FileMode</strong> 枚举定义了各种打开文件的方法。FileMode 枚举的成员有：<strong>Append</strong>：打开一个已有的文件，并将光标放置在文件的末尾。如果文件不存在，则创建文件。<strong>Create</strong>：创建一个新的文件。如果文件已存在，则删除旧文件，然后创建新文件。<strong>CreateNew</strong>：指定操作系统应创建一个新的文件。如果文件已存在，则抛出异常。<strong>Open</strong>：打开一个已有的文件。如果文件不存在，则抛出异常。<strong>OpenOrCreate</strong>：指定操作系统应打开一个已有的文件。如果文件不存在，则用指定的名称创建一个新的文件打开。<strong>Truncate</strong>：打开一个已有的文件，文件一旦打开，就将被截断为零字节大小。然后我们可以向文件写入全新的数据，但是保留文件的初始创建日期。如果文件不存在，则抛出异常。</td>
</tr>
<tr>
<td>FileAccess</td>
<td><strong>FileAccess</strong> 枚举的成员有：<strong>Read</strong>、<strong>ReadWrite</strong> 和 <strong>Write</strong>。</td>
</tr>
<tr>
<td>FileShare</td>
<td><strong>FileShare</strong> 枚举的成员有：<strong>Inheritable</strong>：允许文件句柄可由子进程继承。Win32 不直接支持此功能。<strong>None</strong>：谢绝共享当前文件。文件关闭前，打开该文件的任何请求（由此进程或另一进程发出的请求）都将失败。<strong>Read</strong>：允许随后打开文件读取。如果未指定此标志，则文件关闭前，任何打开该文件以进行读取的请求（由此进程或另一进程发出的请求）都将失败。但是，即使指定了此标志，仍可能需要附加权限才能够访问该文件。<strong>ReadWrite</strong>：允许随后打开文件读取或写入。如果未指定此标志，则文件关闭前，任何打开该文件以进行读取或写入的请求（由此进程或另一进程发出）都将失败。但是，即使指定了此标志，仍可能需要附加权限才能够访问该文件。<strong>Write</strong>：允许随后打开文件写入。如果未指定此标志，则文件关闭前，任何打开该文件以进行写入的请求（由此进程或另一进过程发出的请求）都将失败。但是，即使指定了此标志，仍可能需要附加权限才能够访问该文件。<strong>Delete</strong>：允许随后删除文件。</td>
</tr>
</tbody>
</table>
<p>## </p>
<p>下面的程序演示了 <strong>FileStream</strong> 类的用法：</p>
<blockquote>
<h2 id="实例-39"><a href="#实例-39" class="headerlink" title="实例"></a>实例</h2></blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">using System;</span><br><span class="line">using System.IO;</span><br><span class="line">namespace FileIOApplication</span><br><span class="line">&#123;</span><br><span class="line">    class Program</span><br><span class="line">    &#123;</span><br><span class="line">        static void Main(string[] args)</span><br><span class="line">        &#123;</span><br><span class="line">            FileStream F = new FileStream(&quot;test.dat&quot;, </span><br><span class="line">            FileMode.OpenOrCreate, FileAccess.ReadWrite);</span><br><span class="line">            for (int i = 1; i &lt;= 20; i++)</span><br><span class="line">            &#123;</span><br><span class="line">                F.WriteByte((byte)i);</span><br><span class="line">            &#125;</span><br><span class="line">            F.Position = 0;</span><br><span class="line">            for (int i = 0; i &lt;= 20; i++)</span><br><span class="line">            &#123;</span><br><span class="line">                Console.Write(F.ReadByte() + &quot; &quot;);</span><br><span class="line">            &#125;</span><br><span class="line">            F.Close();</span><br><span class="line">            Console.ReadKey();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1</span><br></pre></td></tr></table></figure>
<h3 id="3-C-高级文件操作"><a href="#3-C-高级文件操作" class="headerlink" title="3. C# 高级文件操作"></a><strong>3. C# 高级文件操作</strong></h3><p>上面的实例演示了 C# 中简单的文件操作。但是，要充分利用 C# System.IO 类的强大功能，您需要知道这些类常用的属性和方法。</p>
<p>在下面的章节中，我们将讨论这些类和它们执行的操作。请单击链接详细了解各个部分的知识：</p>
<table>
<thead>
<tr>
<th>主题</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-text-files.html" target="_blank" rel="noopener">文本文件的读写</a></td>
<td>它涉及到文本文件的读写。<strong>StreamReader</strong> 和 <strong>StreamWriter</strong> 类有助于完成文本文件的读写。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-binary-files.html" target="_blank" rel="noopener">二进制文件的读写</a></td>
<td>它涉及到二进制文件的读写。<strong>BinaryReader</strong> 和 <strong>BinaryWriter</strong> 类有助于完成二进制文件的读写。</td>
</tr>
<tr>
<td><a href="http://www.runoob.com/csharp/csharp-windows-file-system.html" target="_blank" rel="noopener">Windows 文件系统的操作</a></td>
<td>它让 C# 程序员能够浏览并定位 Windows 文件和目录。</td>
</tr>
</tbody>
</table>
<h1 id="C-高级教程"><a href="#C-高级教程" class="headerlink" title="C#高级教程"></a><strong>C#高级教程</strong></h1><h2 id="一-C-特性（Attribute）"><a href="#一-C-特性（Attribute）" class="headerlink" title="一. C# 特性（Attribute）"></a>一. C# 特性（Attribute）</h2><p><strong>特性（Attribute）</strong>是用于在运行时传递程序中各种元素（比如类、方法、结构、枚举、组件等）的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号（[ ]）来描述的。</p>
<p>特性（Attribute）用于添加元数据，如编译器指令和注释、描述、方法、类等其他信息。.Net 框架提供了两种类型的特性：<em>预定义</em>特性和<em>自定义</em>特性。</p>
<h3 id="1-规定特性（Attribute）"><a href="#1-规定特性（Attribute）" class="headerlink" title="1. 规定特性（Attribute）"></a><strong>1. 规定特性（Attribute）</strong></h3><p>规定特性（Attribute）的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[attribute(positional_parameters, name_parameter = value, ...)]</span><br><span class="line">element</span><br></pre></td></tr></table></figure>
<p>特性（Attribute）的名称和值是在方括号内规定的，放置在它所应用的元素之前。positional_parameters 规定必需的信息，name_parameter 规定可选的信息。</p>
<h2 id="预定义特性（Attribute）"><a href="#预定义特性（Attribute）" class="headerlink" title="预定义特性（Attribute）"></a>预定义特性（Attribute）</h2><p>.Net 框架提供了三种预定义特性：</p>
<ul>
<li>AttributeUsage</li>
<li>Conditional</li>
<li>Obsolete</li>
</ul>
<h3 id="AttributeUsage"><a href="#AttributeUsage" class="headerlink" title="AttributeUsage"></a>AttributeUsage</h3><p>预定义特性 <strong>AttributeUsage</strong> 描述了如何使用一个自定义特性类。它规定了特性可应用到的项目的类型。</p>
<p>规定该特性的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[AttributeUsage(</span><br><span class="line">   validon,</span><br><span class="line">   AllowMultiple=allowmultiple,</span><br><span class="line">   Inherited=inherited</span><br><span class="line">)]</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li>参数 validon 规定特性可被放置的语言元素。它是枚举器 <em>AttributeTargets</em> 的值的组合。默认值是 <em>AttributeTargets.All</em>。</li>
<li>参数 <em>allowmultiple</em>（可选的）为该特性的 <em>AllowMultiple</em> 属性（property）提供一个布尔值。如果为 true，则该特性是多用的。默认值是 false（单用的）。</li>
<li>参数 <em>inherited</em>（可选的）为该特性的 <em>Inherited</em> 属性（property）提供一个布尔值。如果为 true，则该特性可被派生类继承。默认值是 false（不被继承）。</li>
</ul>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[AttributeUsage(AttributeTargets.Class |</span><br><span class="line">AttributeTargets.Constructor |</span><br><span class="line">AttributeTargets.Field |</span><br><span class="line">AttributeTargets.Method |</span><br><span class="line">AttributeTargets.Property, </span><br><span class="line">AllowMultiple = true)]</span><br></pre></td></tr></table></figure>
<h3 id="Conditional"><a href="#Conditional" class="headerlink" title="Conditional"></a>Conditional</h3><p>这个预定义特性标记了一个条件方法，其执行依赖于指定的预处理标识符。</p>
<p>它会引起方法调用的条件编译，取决于指定的值，比如 <strong>Debug</strong> 或 <strong>Trace</strong>。例如，当调试代码时显示变量的值。</p>
<p>规定该特性的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[Conditional(</span><br><span class="line">   conditionalSymbol</span><br><span class="line">)]</span><br></pre></td></tr></table></figure>
<p>例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[Conditional(&quot;DEBUG&quot;)]</span><br></pre></td></tr></table></figure>
<p>下面的实例演示了该特性：</p>
<h2 id="实例-40"><a href="#实例-40" class="headerlink" title="实例"></a>实例</h2><p>#define DEBUG<br>using System;<br>using System.Diagnostics;<br>public class Myclass<br>{<br>    [Conditional(“DEBUG”)]<br>    public static void Message(string msg)<br>    {<br>        Console.WriteLine(msg);<br>    }<br>}<br>class Test<br>{<br>    static void function1()<br>    {<br>        Myclass.Message(“In Function 1.”);<br>        function2();<br>    }<br>    static void function2()<br>    {<br>        Myclass.Message(“In Function 2.”);<br>    }<br>    public static void Main()<br>    {<br>        Myclass.Message(“In Main function.”);<br>        function1();<br>        Console.ReadKey();<br>    }<br>}</p>
<p>当上面的代码被编译和执行时，它会产生下列结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">In Main function</span><br><span class="line">In Function 1</span><br><span class="line">In Function 2</span><br></pre></td></tr></table></figure>
<h3 id="Obsolete"><a href="#Obsolete" class="headerlink" title="Obsolete"></a>Obsolete</h3><p>这个预定义特性标记了不应被使用的程序实体。它可以让您通知编译器丢弃某个特定的目标元素。例如，当一个新方法被用在一个类中，但是您仍然想要保持类中的旧方法，您可以通过显示一个应该使用新方法，而不是旧方法的消息，来把它标记为 obsolete（过时的）。</p>
<p>规定该特性的语法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[Obsolete(</span><br><span class="line">   message</span><br><span class="line">)]</span><br><span class="line">[Obsolete(</span><br><span class="line">   message,</span><br><span class="line">   iserror</span><br><span class="line">)]</span><br></pre></td></tr></table></figure>
<p>其中：</p>
<ul>
<li>参数 <em>message</em>，是一个字符串，描述项目为什么过时的原因以及该替代使用什么。</li>
<li>参数 <em>iserror</em>，是一个布尔值。如果该值为 true，编译器应把该项目的使用当作一个错误。默认值是 false（编译器生成一个警告）。</li>
</ul>
<p>下面的实例演示了该特性：</p>
<h2 id="实例-41"><a href="#实例-41" class="headerlink" title="实例"></a>实例</h2><p>using System;<br>public class MyClass<br>{<br>   [Obsolete(“Don’t use OldMethod, use NewMethod instead”, true)]<br>   static void OldMethod()<br>   {<br>      Console.WriteLine(“It is the old method”);<br>   }<br>   static void NewMethod()<br>   {<br>      Console.WriteLine(“It is the new method”);<br>   }<br>   public static void Main()<br>   {<br>      OldMethod();<br>   }<br>}</p>
<p>当您尝试编译该程序时，编译器会给出一个错误消息说明：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Don&apos;t use OldMethod, use NewMethod instead</span><br></pre></td></tr></table></figure>
<h2 id="创建自定义特性（Attribute）"><a href="#创建自定义特性（Attribute）" class="headerlink" title="创建自定义特性（Attribute）"></a>创建自定义特性（Attribute）</h2><p>.Net 框架允许创建自定义特性，用于存储声明性的信息，且可在运行时被检索。该信息根据设计标准和应用程序需要，可与任何目标元素相关。</p>
<p>创建并使用自定义特性包含四个步骤：</p>
<ul>
<li>声明自定义特性</li>
<li>构建自定义特性</li>
<li>在目标程序元素上应用自定义特性</li>
<li>通过反射访问特性</li>
</ul>
<p>最后一个步骤包含编写一个简单的程序来读取元数据以便查找各种符号。元数据是用于描述其他数据的数据和信息。该程序应使用反射来在运行时访问特性。我们将在下一章详细讨论这点。</p>
<h3 id="声明自定义特性"><a href="#声明自定义特性" class="headerlink" title="声明自定义特性"></a>声明自定义特性</h3><p>一个新的自定义特性应派生自 <strong>System.Attribute</strong> 类。例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">// 一个自定义特性 BugFix 被赋给类及其成员</span><br><span class="line">[AttributeUsage(AttributeTargets.Class |</span><br><span class="line">AttributeTargets.Constructor |</span><br><span class="line">AttributeTargets.Field |</span><br><span class="line">AttributeTargets.Method |</span><br><span class="line">AttributeTargets.Property,</span><br><span class="line">AllowMultiple = true)]</span><br><span class="line"></span><br><span class="line">public class DeBugInfo : System.Attribute</span><br></pre></td></tr></table></figure>
<p>在上面的代码中，我们已经声明了一个名为 <em>DeBugInfo</em> 的自定义特性。</p>
<h3 id="构建自定义特性"><a href="#构建自定义特性" class="headerlink" title="构建自定义特性"></a>构建自定义特性</h3><p>让我们构建一个名为 <em>DeBugInfo</em> 的自定义特性，该特性将存储调试程序获得的信息。它存储下面的信息：</p>
<ul>
<li>bug 的代码编号</li>
<li>辨认该 bug 的开发人员名字</li>
<li>最后一次审查该代码的日期</li>
<li>一个存储了开发人员标记的字符串消息</li>
</ul>
<p>我们的 <em>DeBugInfo</em> 类将带有三个用于存储前三个信息的私有属性（property）和一个用于存储消息的公有属性（property）。所以 bug 编号、开发人员名字和审查日期将是 DeBugInfo 类的必需的定位（ positional）参数，消息将是一个可选的命名（named）参数。</p>
<p>每个特性必须至少有一个构造函数。必需的定位（ positional）参数应通过构造函数传递。下面的代码演示了 <em>DeBugInfo</em> 类：</p>
<h2 id="实例-42"><a href="#实例-42" class="headerlink" title="实例"></a>实例</h2><p>// 一个自定义特性 BugFix 被赋给类及其成员<br>[AttributeUsage(AttributeTargets.Class |<br>AttributeTargets.Constructor |<br>AttributeTargets.Field |<br>AttributeTargets.Method |<br>AttributeTargets.Property,<br>AllowMultiple = true)]<br>public class DeBugInfo : System.Attribute<br>{<br>  private int bugNo;<br>  private string developer;<br>  private string lastReview;<br>  public string message;<br>  public DeBugInfo(int bg, string dev, string d)<br>  {<br>      this.bugNo = bg;<br>      this.developer = dev;<br>      this.lastReview = d;<br>  }<br>  public int BugNo<br>  {<br>      get<br>      {<br>          return bugNo;<br>      }<br>  }<br>  public string Developer<br>  {<br>      get<br>      {<br>          return developer;<br>      }<br>  }<br>  public string LastReview<br>  {<br>      get<br>      {<br>          return lastReview;<br>      }<br>  }<br>  public string Message<br>  {<br>      get<br>      {<br>          return message;<br>      }<br>      set<br>      {<br>          message = value;<br>      }<br>  }<br>}</p>
<h3 id="应用自定义特性"><a href="#应用自定义特性" class="headerlink" title="应用自定义特性"></a>应用自定义特性</h3><p>通过把特性放置在紧接着它的目标之前，来应用该特性：</p>
<h2 id="实例-43"><a href="#实例-43" class="headerlink" title="实例"></a>实例</h2><p>[DeBugInfo(45, “Zara Ali”, “12/8/2012”, Message = “Return type mismatch”)]<br>[DeBugInfo(49, “Nuha Ali”, “10/10/2012”, Message = “Unused variable”)]<br>class Rectangle<br>{<br>  // 成员变量<br>  protected double length;<br>  protected double width;<br>  public Rectangle(double l, double w)<br>  {<br>      length = l;<br>      width = w;<br>  }<br>  [DeBugInfo(55, “Zara Ali”, “19/10/2012”,<br>  Message = “Return type mismatch”)]<br>  public double GetArea()<br>  {<br>      return length * width;<br>  }<br>  [DeBugInfo(56, “Zara Ali”, “19/10/2012”)]<br>  public void Display()<br>  {<br>      Console.WriteLine(“Length: {0}”, length);<br>      Console.WriteLine(“Width: {0}”, width);<br>      Console.WriteLine(“Area: {0}”, GetArea());<br>  }<br>}</p>
<p>在下一章中，我们将使用 Reflection 类对象来检索这些信息。</p>
    </div>
  </div>
  
    <div class="copy-right">
      <div class="markdown-body">
        <blockquote>
        
        
          本文作者 : 朽年 <br>
        
        原文链接 : <a href>http://yoursite.com/passages/C-教程/</a><br>
        版权声明 : 本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
        </blockquote>
      </div>
    </div>
  
  
  
    <div class="social-share" style="margin-top: -2rem" data-wechat-qrcode-title="<p>微信扫一扫</p>" data-wechat-qrcode-helper="<p>微信右上角, 扫一扫分享</p>" data-sites="qzone, qq, weibo, wechat, douban, google, facebook, twitter">
  <span style="color: #6b7487; font-size: 1.4rem;">分享到: </span>
</div>
<script src="https://cdn.bootcss.com/social-share.js/1.0.16/js/social-share.min.js" async></script>
  

  
    <div id="reward">
  
    <p id="reward-meta">知识 & 情怀 | 二者兼得</p>
  
  <button id="reward-btn">
    
    <span>投食</span>
  </button>
  <div id="reward-qrcode">
    
      <div class="reward-qrcode--container">
        <img class="qrcode-img" src="https://tangbeida.oss-cn-hangzhou.aliyuncs.com/image/MY_ID/%E5%BE%AE%E4%BF%A1.jpg" alt="微信扫一扫, 向我投食">
        <p class="qrcode-meta">微信扫一扫, 向我投食</p>
      </div>
    
      <div class="reward-qrcode--container">
        <img class="qrcode-img" src="https://tangbeida.oss-cn-hangzhou.aliyuncs.com/image/MY_ID/%E6%94%AF%E4%BB%98%E5%AE%9D.jpg" alt="支付宝扫一扫, 向我投食">
        <p class="qrcode-meta">支付宝扫一扫, 向我投食</p>
      </div>
    
  </div>

</div>

<script>
  (() => {
    let button = document.querySelector('#reward-btn'),
      qrcode = document.querySelector('#reward-qrcode'),
      display = false;
    
    button.addEventListener('click', () => {
      qrcode.style.display = display ? 'none' : 'block'
      display = !display
    }, false)
  })()
</script>
  

  <div class="article-footer">
    <div class="article-meta pull-left">
      <span>
        
          <i class="iconfont icon-06tags"></i>标签: 
          
          <span class="span--tag">
            <a href="/tags/笔记/">
              #笔记
            </a>
          </span>
          
          <span class="span--tag">
            <a href="/tags/C/">
              #C#
            </a>
          </span>
          
        
      </span>
    </div>
    <div class="article-meta pull-right">
    </div>
  </div>
</div>


  <aside id="sidebar">
    <p id="sidebar-header"></p>
    <ol id="sidebar-toc"></ol>
  </aside>
  <script async>setTimeout(generateToc, 10);</script>


  <nav class="post-navigation">
    
      <div class="nav-pre">
        <i class="iconfont icon-prev"></i>
        上一篇:
        <a href="/passages/matlab学习笔记/" target="_self">Matlab学习笔记</a>
      </div>
    
    
      <div class="nav-next">
        下一篇:
        <a href="/passages/最实用的网站大全/" target="_self">最实用的网站大全</a>
        <i class="iconfont icon-next"></i>
      </div>
    
  </nav>

  
    <a href="#comment" class="comment-anchor"></a>
<div class="comment-title"><i class="iconfont icon-footprint"></i> 留下足迹 <i class="iconfont icon-footprint"></i></div>
<div id="vcomments"></div>

<script defer>
  if( true ) {
    let path = getRealPath()
    new Valine({
      el: "#vcomments",
      appId: "5Sml225fSWFOKRJENmDKJ9zq-gzGzoHsz",
      appKey: "mUMq9vR0KdKnzhpos9uPpyXo",
      notify: false,
      verify: false,
      avatar: "robohash",
      placeholder: "正确填写邮箱, 才能及时收到回复哦♪(^∇^*)",
      path
    });
  }
</script>
   

  
    <script defer>
const valineAPI = (() => {
  try {
    AV.init("5Sml225fSWFOKRJENmDKJ9zq-gzGzoHsz", "mUMq9vR0KdKnzhpos9uPpyXo");
  } catch(error) {}
  const isExist = (identity) => {
    identity = identity || getRealPath();
    let query = new AV.Query('Timer');
    return new Promise((resolve, reject) => {
      query.equalTo("identity", identity);
      query.find().then(results => {
        resolve(results.length > 0);
      }, error => reject(error));
    })
  }

  const _get = (identity) => {
    let query = null;
    if(identity && identity instanceof Array){
      let querys = [];
      for(let i = 0; i < identity.length; ++i) {
        querys[i] = new AV.Query('Timer');
        querys[i].equalTo('identity', identity[i]);
      }
      query = AV.Query.or.apply(null ,querys);
    } else {
      identity = identity || getRealPath();
      query = new AV.Query("Timer");
      query.equalTo("identity", identity);
    }

    return new Promise((resolve, reject) => {
      query.find()
      .then(results => resolve(results))
      .catch(error => reject(error))
    })
  }

  const create = (identity) => {
    identity = identity || getRealPath();
    return new Promise((resolve, reject) => {
      let Todo = AV.Object.extend('Timer');
      let todo = new Todo();
      todo.set("times", 1);
      todo.set("identity", identity);
      todo.save().then(res => resolve(true), error => reject(error));
    })
  }

  const update = (identity) => {
    identity = identity || getRealPath();
    return new Promise((resolve, reject) => {
      let query = new AV.Query('Timer');
      query.equalTo("identity", identity);
      query.find().then(todos => {
        todos.forEach(todo => {
          todo.set("times", todo.attributes.times + 1);
        });
        return AV.Object.saveAll(todos);
      }).then(todos => resolve(true), error => reject(error));
    })
  }

  return {
    isExist,
    _get,
    update,
    create
  }
})()

const calcAndWriteTimes = () => {
  let isPost = true;

  let timerAllDOM = document.querySelectorAll(".article-timer");

  if(isPost) {
    let identity = timerAllDOM[0].getAttribute("data-identity");
    valineAPI.isExist(identity)
    .then(exist => {
      if(exist) {
        return valineAPI.update(identity);
      }
      return new Promise(resolve => resolve(true));
    })
    .then( succuess => valineAPI._get(identity))
    .then( result => timerAllDOM[0].innerText = result[0].attributes.times)
    .catch(error => console.log(error.message))
    return ;
  }

  let timerDOMCache = {};

  for(let timerDOM of timerAllDOM) {
    let identity = timerDOM.getAttribute("data-identity");
    if(timerDOMCache.hasOwnProperty(identity)){
      timerDOMCache[identity].dom.push(timerDOM);
    }else{
      timerDOMCache[identity] = {
        dom: [timerDOM],
        times: undefined
      };
    }
  }

  let identities = Object.keys(timerDOMCache);
  valineAPI._get(identities).then(results => {
    for(let result of results) {
      let {identity, times} = result.attributes;
      timerDOMCache[identity].times = times;
      timerDOMCache[identity].dom.map(item => item.innerText = times);
    }
    for(let identity of identities) {
      if(timerDOMCache[identity].times){
        continue;
      }
      timerDOMCache[identity].dom.map(item => item.innerText = 1);
      valineAPI.create(identity);
    }
  }).catch(error => console.log(error.message))
}

if(true){
  calcAndWriteTimes();
}
</script>
   

</div>


      <footer>
  <p class="site-info">
    博客已萌萌哒运行<span id="time-to-now"></span><span class="my-face">(●'◡'●)ﾉ♥</span>
    <br>
    Theme - <a href="https://github.com/dongyuanxin/theme-bmw">BMW</a> | Made With 💗 | Powered by <a href="https://godbmw.com/">GodBMW</a>
    <br>
    
      <a href="https://www.google.com/analytics/" target="_blank">Google Analytics</a>提供统计服务
    
  </p>
</footer>



<script>
const timeToNowDOM = document.querySelector("#time-to-now");
const startTimestamp = new Date(2017, 3, 29).getTime();

const updateTimeStr = () => {
  let offset = parseInt(
      (new Date().getTime() - startTimestamp) / 1000,
      10
    ),
    day = Math.floor(offset / 86400),
    hour = Math.floor((offset % 86400) / 3600),
    minute = Math.floor(((offset % 86400) % 3600) / 60),
    second = Math.floor(((offset % 86400) % 3600) % 60);
  timeToNowDOM.innerHTML =
    day + "天" + hour + "小时" + minute + "分钟" + second + "秒";
  setTimeout(updateTimeStr, 500);
}

setTimeout(updateTimeStr, 500);
</script>


      <div class="back-to-top hidden">
  <span>
    <i class="iconfont icon-60"></i><span></span>%
  </span>
</div>

<script>
const updateIconToTop = percent => {
  let dom = document.querySelector(".back-to-top span span");
  dom.innerText = percent;
  if(percent < 1) {
    document.querySelector(".back-to-top").className = "back-to-top hidden";
  } else {
    document.querySelector(".back-to-top").className = "back-to-top";
  }
}

const handleScoll = () => {
  let isRunning = false;
  return () => {
    if (isRunning) return;
    isRunning = true;
    window.requestAnimationFrame(timestamp => {
      let scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop,
        scrollHeight =
          document.documentElement.scrollHeight ||
          document.body.scrollHeight,
        clientHeight =
          document.documentElement.clientHeight ||
          document.body.clientHeight;
      isRunning = false;
      if (scrollTop <= 1) {
        updateIconToTop(0);
        return;
      }
      if (scrollTop + clientHeight >= scrollHeight) {
        updateIconToTop(100);
      } else {
        updateIconToTop(parseInt(
          100 * scrollTop / (scrollHeight - clientHeight),
          10
        ));
      }
    });
  };
}

const backToTop = () => {
  let scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop,
    delay = 10,
    time = 200;
  if (scrollTop <= 20) {
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    return;
  }
  let step = Math.ceil(scrollTop * delay / time);
  let timer = setInterval(() => {
    scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop - step <= 0) {
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      clearInterval(timer);
    } else {
      document.documentElement.scrollTop = scrollTop - step;
      document.body.scrollTop = scrollTop - step;
    }
  }, delay);
}

document.addEventListener("scroll", handleScoll(), false);

document.querySelector(".back-to-top").addEventListener("click", backToTop, false);

</script>

    </div>

    
      <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async></script>
<script>
  (() => {
    const mathjaxConfig = {
      showProcessingMessages: false, //关闭js加载过程信息
      messageStyle: "none", //不显示信息
      jax: ["input/TeX", "output/HTML-CSS"],
      tex2jax: {
        inlineMath: [["$", "$"], ["\\(", "\\)"]], //行内公式选择符
        displayMath: [["$$", "$$"], ["\\[", "\\]"]], //段内公式选择符
        skipTags: ["script", "noscript", "style", "textarea", "pre", "code", "a"] //避开某些标签
      },
      "HTML-CSS": {
        availableFonts: ["STIX", "TeX"], //可选字体
        showMathMenu: false //关闭右击菜单显示
      }
    }

    let mathjaxInterval = setInterval(() => {
      if(!window.MathJax){
        return;
      }
      window.MathJax.Hub.Config(mathjaxConfig)
      window.MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById('app')])

      clearInterval(mathjaxInterval)
    }, 10)    
  })()
</script>
    

    <script src="https://cdn.bootcss.com/fancybox/3.5.2/jquery.fancybox.min.js" async></script>
<script async>
  let fancyTimer = setInterval(function(){
    if(!window.$){
      return;
    }
    $(document).ready(function() {
      $(".post img").each(function () {
        if($(this).parent().get(0).tagName.toLowerCase() === "a") {
          return;
        }
        // $(this).attr("data-fancybox", "gallery"); // if you add 'data-fancybox', img will display after showed
        var element = document.createElement("a");
        $(element).attr("data-fancybox", "gallery");
        $(element).attr("href", $(this).attr("src"));
        $(this).wrap(element);
      });
      
      clearInterval(fancyTimer);
    });
  }, 10);
</script>

    
  </body>

</html>
